__init__.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. # pylint: disable=invalid-name
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2014-2015
  7. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This library is free software; you can redistribute it and/or
  11. # modify it under the terms of the GNU Lesser General Public
  12. # License as published by the Free Software Foundation; either
  13. # version 2.1 of the License, or (at your option) any later version.
  14. #
  15. # This library is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. # Lesser General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Lesser General Public
  21. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  22. #
  23. """
  24. .. warning::
  25. The test suite hereby claims any domain whose name starts with
  26. :py:data:`VMPREFIX` as fair game. This is needed to enforce sane
  27. test executing environment. If you have domains named ``test-*``,
  28. don't run the tests.
  29. """
  30. import asyncio
  31. import collections
  32. import functools
  33. import logging
  34. import os
  35. import pathlib
  36. import shlex
  37. import shutil
  38. import subprocess
  39. import sys
  40. import tempfile
  41. import time
  42. import traceback
  43. import unittest
  44. import warnings
  45. from distutils import spawn
  46. import gc
  47. import lxml.etree
  48. import pkg_resources
  49. import qubes
  50. import qubes.api
  51. import qubes.api.admin
  52. import qubes.api.internal
  53. import qubes.backup
  54. import qubes.config
  55. import qubes.devices
  56. import qubes.events
  57. import qubes.exc
  58. import qubes.vm.standalonevm
  59. import qubes.vm.templatevm
  60. XMLPATH = '/var/lib/qubes/qubes-test.xml'
  61. CLASS_XMLPATH = '/var/lib/qubes/qubes-class-test.xml'
  62. TEMPLATE = 'fedora-23'
  63. VMPREFIX = 'test-inst-'
  64. CLSVMPREFIX = 'test-cls-'
  65. if 'DEFAULT_LVM_POOL' in os.environ.keys():
  66. DEFAULT_LVM_POOL = os.environ['DEFAULT_LVM_POOL']
  67. else:
  68. DEFAULT_LVM_POOL = 'qubes_dom0/pool00'
  69. POOL_CONF = {'name': 'test-lvm',
  70. 'driver': 'lvm_thin',
  71. 'volume_group': DEFAULT_LVM_POOL.split('/')[0],
  72. 'thin_pool': DEFAULT_LVM_POOL.split('/')[1]}
  73. #: :py:obj:`True` if running in dom0, :py:obj:`False` otherwise
  74. in_dom0 = False
  75. #: :py:obj:`False` if outside of git repo,
  76. #: path to root of the directory otherwise
  77. in_git = False
  78. try:
  79. import libvirt
  80. libvirt.openReadOnly(qubes.config.defaults['libvirt_uri']).close()
  81. in_dom0 = True
  82. except libvirt.libvirtError:
  83. pass
  84. if in_dom0:
  85. import libvirtaio
  86. libvirt_event_impl = libvirtaio.virEventRegisterAsyncIOImpl()
  87. else:
  88. libvirt_event_impl = None
  89. try:
  90. in_git = subprocess.check_output(
  91. ['git', 'rev-parse', '--show-toplevel']).decode().strip()
  92. qubes.log.LOGPATH = '/tmp'
  93. qubes.log.LOGFILE = '/tmp/qubes.log'
  94. except subprocess.CalledProcessError:
  95. # git returned nonzero, we are outside git repo
  96. pass
  97. except OSError:
  98. # command not found; let's assume we're outside
  99. pass
  100. def skipUnlessDom0(test_item):
  101. '''Decorator that skips test outside dom0.
  102. Some tests (especially integration tests) have to be run in more or less
  103. working dom0. This is checked by connecting to libvirt.
  104. '''
  105. return unittest.skipUnless(in_dom0, 'outside dom0')(test_item)
  106. def skipUnlessGit(test_item):
  107. '''Decorator that skips test outside git repo.
  108. There are very few tests that an be run only in git. One example is
  109. correctness of example code that won't get included in RPM.
  110. '''
  111. return unittest.skipUnless(in_git, 'outside git tree')(test_item)
  112. def skipUnlessEnv(varname):
  113. '''Decorator generator for skipping tests without environment variable set.
  114. Some tests require working X11 display, like those using GTK library, which
  115. segfaults without connection to X.
  116. Other require their own, custom variables.
  117. '''
  118. return unittest.skipUnless(os.getenv(varname), 'no {} set'.format(varname))
  119. class TestEmitter(qubes.events.Emitter):
  120. '''Dummy event emitter which records events fired on it.
  121. Events are counted in :py:attr:`fired_events` attribute, which is
  122. :py:class:`collections.Counter` instance. For each event, ``(event, args,
  123. kwargs)`` object is counted. *event* is event name (a string), *args* is
  124. tuple with positional arguments and *kwargs* is sorted tuple of items from
  125. keyword arguments.
  126. >>> emitter = TestEmitter()
  127. >>> emitter.fired_events
  128. Counter()
  129. >>> emitter.fire_event('event', spam='eggs', foo='bar')
  130. >>> emitter.fired_events
  131. Counter({('event', (1, 2, 3), (('foo', 'bar'), ('spam', 'eggs'))): 1})
  132. '''
  133. def __init__(self, *args, **kwargs):
  134. super(TestEmitter, self).__init__(*args, **kwargs)
  135. #: :py:class:`collections.Counter` instance
  136. self.fired_events = collections.Counter()
  137. def fire_event(self, event, **kwargs):
  138. effects = super(TestEmitter, self).fire_event(event, **kwargs)
  139. ev_kwargs = frozenset(
  140. (key,
  141. frozenset(value.items()) if isinstance(value, dict)
  142. else tuple(value) if isinstance(value, list)
  143. else value)
  144. for key, value in kwargs.items()
  145. )
  146. self.fired_events[(event, ev_kwargs)] += 1
  147. return effects
  148. @asyncio.coroutine
  149. def fire_event_async(self, event, pre_event=False, **kwargs):
  150. effects = yield from super(TestEmitter, self).fire_event_async(
  151. event, pre_event=pre_event, **kwargs)
  152. ev_kwargs = frozenset(
  153. (key,
  154. frozenset(value.items()) if isinstance(value, dict) else value)
  155. for key, value in kwargs.items()
  156. )
  157. self.fired_events[(event, ev_kwargs)] += 1
  158. return effects
  159. def expectedFailureIfTemplate(templates):
  160. """
  161. Decorator for marking specific test as expected to fail only for some
  162. templates. Template name is compared as substring, so 'whonix' will
  163. handle both 'whonix-ws' and 'whonix-gw'.
  164. templates can be either a single string, or an iterable
  165. """
  166. def decorator(func):
  167. @functools.wraps(func)
  168. def wrapper(self, *args, **kwargs):
  169. template = self.template
  170. if isinstance(templates, str):
  171. should_expect_fail = template in templates
  172. else:
  173. should_expect_fail = any([template in x for x in templates])
  174. if should_expect_fail:
  175. try:
  176. func(self, *args, **kwargs)
  177. except Exception:
  178. raise unittest.case._ExpectedFailure(sys.exc_info())
  179. raise unittest.case._UnexpectedSuccess()
  180. else:
  181. # Call directly:
  182. func(self, *args, **kwargs)
  183. return wrapper
  184. return decorator
  185. class _AssertNotRaisesContext(object):
  186. """A context manager used to implement TestCase.assertNotRaises methods.
  187. Stolen from unittest and hacked. Regexp support stripped.
  188. """ # pylint: disable=too-few-public-methods
  189. def __init__(self, expected, test_case, expected_regexp=None):
  190. if expected_regexp is not None:
  191. raise NotImplementedError('expected_regexp is unsupported')
  192. self.expected = expected
  193. self.exception = None
  194. self.failureException = test_case.failureException
  195. def __enter__(self):
  196. return self
  197. def __exit__(self, exc_type, exc_value, tb):
  198. if exc_type is None:
  199. return True
  200. if issubclass(exc_type, self.expected):
  201. raise self.failureException(
  202. "{!r} raised, traceback:\n{!s}".format(
  203. exc_value, ''.join(traceback.format_tb(tb))))
  204. else:
  205. # pass through
  206. return False
  207. self.exception = exc_value # store for later retrieval
  208. class _QrexecPolicyContext(object):
  209. '''Context manager for SystemTestCase.qrexec_policy'''
  210. def __init__(self, service, source, destination, allow=True, action=None):
  211. try:
  212. source = source.name
  213. except AttributeError:
  214. pass
  215. try:
  216. destination = destination.name
  217. except AttributeError:
  218. pass
  219. self._filename = pathlib.Path('/etc/qubes-rpc/policy') / service
  220. if action is None:
  221. action = 'allow' if allow else 'deny'
  222. self._rule = '{} {} {}\n'.format(source, destination, action)
  223. self._did_create = False
  224. self._handle = None
  225. def load(self):
  226. if self._handle is None:
  227. try:
  228. self._handle = self._filename.open('r+')
  229. except FileNotFoundError:
  230. self._handle = self._filename.open('w+')
  231. self._did_create = True
  232. self._handle.seek(0)
  233. return self._handle.readlines()
  234. def save(self, rules):
  235. assert self._handle is not None
  236. self._handle.truncate(0)
  237. self._handle.seek(0)
  238. self._handle.write(''.join(rules))
  239. self._handle.flush()
  240. def close(self):
  241. assert self._handle is not None
  242. self._handle.close()
  243. self._handle = None
  244. def __enter__(self):
  245. rules = self.load()
  246. rules.insert(0, self._rule)
  247. self.save(self._rule)
  248. return self
  249. def __exit__(self, exc_type, exc_value, tb):
  250. if not self._did_create:
  251. try:
  252. rules = self.load()
  253. rules.remove(self._rule)
  254. self.save(rules)
  255. finally:
  256. self.close()
  257. else:
  258. self.close()
  259. self._filename.unlink()
  260. class substitute_entry_points(object):
  261. '''Monkey-patch pkg_resources to substitute one group in iter_entry_points
  262. This is for testing plugins, like device classes.
  263. :param str group: The group that is to be overloaded.
  264. :param str tempgroup: The substitute group.
  265. Inside this context, if one iterates over entry points in overloaded group,
  266. the iteration actually happens over the other group.
  267. This context manager is stackable. To substitute more than one entry point
  268. group, just nest two contexts.
  269. ''' # pylint: disable=invalid-name
  270. def __init__(self, group, tempgroup):
  271. self.group = group
  272. self.tempgroup = tempgroup
  273. self._orig_iter_entry_points = None
  274. def _iter_entry_points(self, group, *args, **kwargs):
  275. if group == self.group:
  276. group = self.tempgroup
  277. return self._orig_iter_entry_points(group, *args, **kwargs)
  278. def __enter__(self):
  279. self._orig_iter_entry_points = pkg_resources.iter_entry_points
  280. pkg_resources.iter_entry_points = self._iter_entry_points
  281. return self
  282. def __exit__(self, exc_type, exc_value, tb):
  283. pkg_resources.iter_entry_points = self._orig_iter_entry_points
  284. self._orig_iter_entry_points = None
  285. class QubesTestCase(unittest.TestCase):
  286. '''Base class for Qubes unit tests.
  287. '''
  288. def __init__(self, *args, **kwargs):
  289. super(QubesTestCase, self).__init__(*args, **kwargs)
  290. self.longMessage = True
  291. self.log = logging.getLogger('{}.{}.{}'.format(
  292. self.__class__.__module__,
  293. self.__class__.__name__,
  294. self._testMethodName))
  295. self.addTypeEqualityFunc(qubes.devices.DeviceManager,
  296. self.assertDevicesEqual)
  297. self.loop = None
  298. def __str__(self):
  299. return '{}/{}/{}'.format(
  300. self.__class__.__module__,
  301. self.__class__.__name__,
  302. self._testMethodName)
  303. def setUp(self):
  304. super().setUp()
  305. self.addCleanup(self.cleanup_gc)
  306. self.loop = asyncio.get_event_loop()
  307. self.addCleanup(self.cleanup_loop)
  308. def cleanup_gc(self):
  309. gc.collect()
  310. leaked = [obj for obj in gc.get_objects() + gc.garbage
  311. if isinstance(obj,
  312. (qubes.Qubes, qubes.vm.BaseVM,
  313. libvirt.virConnect, libvirt.virDomain))]
  314. if leaked:
  315. try:
  316. import objgraph
  317. objgraph.show_backrefs(leaked,
  318. max_depth=15, extra_info=extra_info,
  319. filename='/tmp/objgraph-{}.png'.format(self.id()))
  320. except ImportError:
  321. pass
  322. assert not leaked
  323. def cleanup_loop(self):
  324. '''Check if the loop is empty'''
  325. # XXX BEWARE this is touching undocumented, implementation-specific
  326. # attributes of the loop. This is most certainly unsupported and likely
  327. # will break when messing with: Python version, kernel family, loop
  328. # implementation, a combination thereof, or other things.
  329. # KEYWORDS for searching:
  330. # win32, SelectorEventLoop, ProactorEventLoop, uvloop, gevent
  331. global libvirt_event_impl
  332. # Check for unfinished libvirt business.
  333. if libvirt_event_impl is not None:
  334. try:
  335. self.loop.run_until_complete(asyncio.wait_for(
  336. libvirt_event_impl.drain(), timeout=4))
  337. except asyncio.TimeoutError:
  338. raise AssertionError('libvirt event impl drain timeout')
  339. # Check there are no Tasks left.
  340. assert not self.loop._ready
  341. assert not self.loop._scheduled
  342. # Check the loop watches no descriptors.
  343. # NOTE the loop has a pipe for self-interrupting, created once per
  344. # lifecycle, and it is unwatched only at loop.close(); so we cannot just
  345. # check selector for non-emptiness
  346. assert len(self.loop._selector.get_map()) \
  347. == int(self.loop._ssock is not None)
  348. del self.loop
  349. def assertNotRaises(self, excClass, callableObj=None, *args, **kwargs):
  350. """Fail if an exception of class excClass is raised
  351. by callableObj when invoked with arguments args and keyword
  352. arguments kwargs. If a different type of exception is
  353. raised, it will not be caught, and the test case will be
  354. deemed to have suffered an error, exactly as for an
  355. unexpected exception.
  356. If called with callableObj omitted or None, will return a
  357. context object used like this::
  358. with self.assertRaises(SomeException):
  359. do_something()
  360. The context manager keeps a reference to the exception as
  361. the 'exception' attribute. This allows you to inspect the
  362. exception after the assertion::
  363. with self.assertRaises(SomeException) as cm:
  364. do_something()
  365. the_exception = cm.exception
  366. self.assertEqual(the_exception.error_code, 3)
  367. """
  368. context = _AssertNotRaisesContext(excClass, self)
  369. if callableObj is None:
  370. return context
  371. with context:
  372. callableObj(*args, **kwargs)
  373. def assertXMLEqual(self, xml1, xml2, msg=''):
  374. '''Check for equality of two XML objects.
  375. :param xml1: first element
  376. :param xml2: second element
  377. :type xml1: :py:class:`lxml.etree._Element`
  378. :type xml2: :py:class:`lxml.etree._Element`
  379. '''
  380. self.assertEqual(xml1.tag, xml2.tag)
  381. msg += '/' + str(xml1.tag)
  382. if xml1.text is not None and xml2.text is not None:
  383. self.assertEqual(xml1.text.strip(), xml2.text.strip(), msg)
  384. else:
  385. self.assertEqual(xml1.text, xml2.text, msg)
  386. self.assertCountEqual(xml1.keys(), xml2.keys(), msg)
  387. for key in xml1.keys():
  388. self.assertEqual(xml1.get(key), xml2.get(key), msg)
  389. self.assertEqual(len(xml1), len(xml2), msg + ' children count')
  390. for child1, child2 in zip(xml1, xml2):
  391. self.assertXMLEqual(child1, child2, msg=msg)
  392. def assertDevicesEqual(self, devices1, devices2, msg=None):
  393. self.assertEqual(devices1.keys(), devices2.keys(), msg)
  394. for dev_class in devices1.keys():
  395. self.assertEqual(
  396. [str(dev) for dev in devices1[dev_class]],
  397. [str(dev) for dev in devices2[dev_class]],
  398. "Devices of class {} differs{}".format(
  399. dev_class, (": " + msg) if msg else "")
  400. )
  401. def assertEventFired(self, subject, event, kwargs=None):
  402. '''Check whether event was fired on given emitter and fail if it did
  403. not.
  404. :param subject: emitter which is being checked
  405. :type emitter: :py:class:`TestEmitter`
  406. :param str event: event identifier
  407. :param 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. # avoid race with DispVM.auto_cleanup=True
  614. try:
  615. self.loop.run_until_complete(
  616. asyncio.wait_for(vm.startup_lock.acquire(), 10))
  617. except asyncio.TimeoutError:
  618. pass
  619. try:
  620. # XXX .is_running() may throw libvirtError if undefined
  621. if vm.is_running():
  622. self.loop.run_until_complete(vm.kill())
  623. except: # pylint: disable=bare-except
  624. pass
  625. try:
  626. self.loop.run_until_complete(vm.remove_from_disk())
  627. except: # pylint: disable=bare-except
  628. pass
  629. try:
  630. del app.domains[vm.qid]
  631. except KeyError:
  632. pass
  633. vm.close()
  634. del vm
  635. app.save()
  636. del app
  637. # Now ensure it really went away. This may not have happened,
  638. # for example if vm.libvirt_domain malfunctioned.
  639. try:
  640. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  641. except: # pylint: disable=bare-except
  642. pass
  643. else:
  644. try:
  645. dom = conn.lookupByName(vmname)
  646. except: # pylint: disable=bare-except
  647. pass
  648. else:
  649. self._remove_vm_libvirt(dom)
  650. conn.close()
  651. self._remove_vm_disk(vmname)
  652. @staticmethod
  653. def _remove_vm_libvirt(dom):
  654. try:
  655. dom.destroy()
  656. except libvirt.libvirtError: # not running
  657. pass
  658. dom.undefine()
  659. @staticmethod
  660. def _remove_vm_disk(vmname):
  661. for dirspec in (
  662. 'qubes_appvms_dir',
  663. 'qubes_servicevms_dir',
  664. 'qubes_templates_dir'):
  665. dirpath = os.path.join(qubes.config.qubes_base_dir,
  666. qubes.config.system_path[dirspec], vmname)
  667. if os.path.exists(dirpath):
  668. if os.path.isdir(dirpath):
  669. shutil.rmtree(dirpath)
  670. else:
  671. os.unlink(dirpath)
  672. @staticmethod
  673. def _remove_vm_disk_lvm(prefix=VMPREFIX):
  674. ''' Remove LVM volumes with given prefix
  675. This is "a bit" drastic, as it removes volumes regardless of volume
  676. group, thin pool etc. But we assume no important data on test system.
  677. '''
  678. try:
  679. volumes = subprocess.check_output(
  680. ['sudo', 'lvs', '--noheadings', '-o', 'vg_name,name',
  681. '--separator', '/']).decode()
  682. if ('/vm-' + prefix) not in volumes:
  683. return
  684. subprocess.check_call(['sudo', 'lvremove', '-f'] +
  685. [vol.strip() for vol in volumes.splitlines()
  686. if ('/vm-' + prefix) in vol],
  687. stdout=subprocess.DEVNULL)
  688. except subprocess.CalledProcessError:
  689. pass
  690. def remove_vms(self, vms):
  691. vms = list(vms)
  692. if not vms:
  693. return
  694. # break dependencies
  695. for vm in vms:
  696. vm.default_dispvm = None
  697. # then remove in reverse topological order (wrt netvm), using naive
  698. # algorithm
  699. # this heavily depends on lack of netvm loops
  700. while vms:
  701. vm = vms.pop(0)
  702. # make sure that all connected VMs are going to be removed,
  703. # otherwise this will loop forever
  704. assert all(x in vms for x in vm.connected_vms)
  705. if list(vm.connected_vms):
  706. # if still something use this VM, put it at the end of queue
  707. # and try next one
  708. vms.append(vm)
  709. continue
  710. self._remove_vm_qubes(vm)
  711. def remove_test_vms(self, xmlpath=XMLPATH, prefix=VMPREFIX):
  712. '''Aggresively remove any domain that has name in testing namespace.
  713. '''
  714. # first, remove them Qubes-way
  715. if os.path.exists(xmlpath):
  716. try:
  717. try:
  718. app = self.app
  719. except AttributeError:
  720. app = qubes.Qubes(xmlpath)
  721. try:
  722. host_app = self.host_app
  723. except AttributeError:
  724. host_app = qubes.Qubes()
  725. self.remove_vms([vm for vm in app.domains
  726. if vm.name.startswith(prefix) or
  727. (isinstance(vm, qubes.vm.dispvm.DispVM) and vm.name
  728. not in host_app.domains)])
  729. if not hasattr(self, 'host_app'):
  730. host_app.close()
  731. del host_app
  732. if not hasattr(self, 'app'):
  733. app.close()
  734. del app
  735. except qubes.exc.QubesException:
  736. pass
  737. os.unlink(xmlpath)
  738. # now remove what was only in libvirt
  739. conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  740. for dom in conn.listAllDomains():
  741. if dom.name().startswith(prefix):
  742. self._remove_vm_libvirt(dom)
  743. conn.close()
  744. # finally remove anything that is left on disk
  745. vmnames = set()
  746. for dirspec in (
  747. 'qubes_appvms_dir',
  748. 'qubes_servicevms_dir',
  749. 'qubes_templates_dir'):
  750. dirpath = os.path.join(qubes.config.qubes_base_dir,
  751. qubes.config.system_path[dirspec])
  752. if not os.path.exists(dirpath):
  753. continue
  754. for name in os.listdir(dirpath):
  755. if name.startswith(prefix):
  756. vmnames.add(name)
  757. for vmname in vmnames:
  758. self._remove_vm_disk(vmname)
  759. self._remove_vm_disk_lvm(prefix)
  760. def qrexec_policy(self, service, source, destination, allow=True,
  761. action=None):
  762. """
  763. Allow qrexec calls for duration of the test
  764. :param service: service name
  765. :param source: source VM name
  766. :param destination: destination VM name
  767. :param allow: add rule with 'allow' action, otherwise 'deny'
  768. :param action: custom action, if specified *allow* argument is ignored
  769. :return:
  770. """
  771. return _QrexecPolicyContext(service, source, destination,
  772. allow=allow, action=action)
  773. def wait_for_window(self, title, timeout=30, show=True):
  774. """
  775. Wait for a window with a given title. Depending on show parameter,
  776. it will wait for either window to show or to disappear.
  777. :param title: title of the window to wait for
  778. :param timeout: timeout of the operation, in seconds
  779. :param show: if True - wait for the window to be visible,
  780. otherwise - to not be visible
  781. :return: None
  782. """
  783. wait_count = 0
  784. while subprocess.call(['xdotool', 'search', '--name', title],
  785. stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) \
  786. == int(not show):
  787. wait_count += 1
  788. if wait_count > timeout*10:
  789. self.fail("Timeout while waiting for {} window to {}".format(
  790. title, "show" if show else "hide")
  791. )
  792. time.sleep(0.1)
  793. def enter_keys_in_window(self, title, keys):
  794. """
  795. Search for window with given title, then enter listed keys there.
  796. The function will wait for said window to appear.
  797. :param title: title of window
  798. :param keys: list of keys to enter, as for `xdotool key`
  799. :return: None
  800. """
  801. # 'xdotool search --sync' sometimes crashes on some race when
  802. # accessing window properties
  803. self.wait_for_window(title)
  804. command = ['xdotool', 'search', '--name', title,
  805. 'windowactivate', '--sync',
  806. 'key'] + keys
  807. subprocess.check_call(command)
  808. def shutdown_and_wait(self, vm, timeout=60):
  809. self.loop.run_until_complete(vm.shutdown())
  810. while timeout > 0:
  811. if not vm.is_running():
  812. return
  813. self.loop.run_until_complete(asyncio.sleep(1))
  814. timeout -= 1
  815. name = vm.name
  816. del vm
  817. self.fail("Timeout while waiting for VM {} shutdown".format(name))
  818. def prepare_hvm_system_linux(self, vm, init_script, extra_files=None):
  819. if not os.path.exists('/usr/lib/grub/i386-pc'):
  820. self.skipTest('grub2 not installed')
  821. if not spawn.find_executable('grub2-install'):
  822. self.skipTest('grub2-tools not installed')
  823. if not spawn.find_executable('dracut'):
  824. self.skipTest('dracut not installed')
  825. # create a single partition
  826. p = subprocess.Popen(['sfdisk', '-q', '-L', vm.storage.root_img],
  827. stdin=subprocess.PIPE,
  828. stdout=subprocess.DEVNULL,
  829. stderr=subprocess.STDOUT)
  830. p.communicate('2048,\n')
  831. assert p.returncode == 0, 'sfdisk failed'
  832. # TODO: check if root_img is really file, not already block device
  833. p = subprocess.Popen(['sudo', 'losetup', '-f', '-P', '--show',
  834. vm.storage.root_img], stdout=subprocess.PIPE)
  835. (loopdev, _) = p.communicate()
  836. loopdev = loopdev.strip()
  837. looppart = loopdev + 'p1'
  838. assert p.returncode == 0, 'losetup failed'
  839. subprocess.check_call(['sudo', 'mkfs.ext2', '-q', '-F', looppart])
  840. mountpoint = tempfile.mkdtemp()
  841. subprocess.check_call(['sudo', 'mount', looppart, mountpoint])
  842. try:
  843. subprocess.check_call(['sudo', 'grub2-install',
  844. '--target', 'i386-pc',
  845. '--modules', 'part_msdos ext2',
  846. '--boot-directory', mountpoint, loopdev],
  847. stderr=subprocess.DEVNULL
  848. )
  849. grub_cfg = '{}/grub2/grub.cfg'.format(mountpoint)
  850. subprocess.check_call(
  851. ['sudo', 'chown', '-R', os.getlogin(), mountpoint])
  852. with open(grub_cfg, 'w') as f:
  853. f.write(
  854. "set timeout=1\n"
  855. "menuentry 'Default' {\n"
  856. " linux /vmlinuz root=/dev/xvda1 "
  857. "rd.driver.blacklist=bochs_drm "
  858. "rd.driver.blacklist=uhci_hcd console=hvc0\n"
  859. " initrd /initrd\n"
  860. "}"
  861. )
  862. p = subprocess.Popen(['uname', '-r'], stdout=subprocess.PIPE)
  863. (kernel_version, _) = p.communicate()
  864. kernel_version = kernel_version.strip()
  865. kernel = '/boot/vmlinuz-{}'.format(kernel_version)
  866. shutil.copy(kernel, os.path.join(mountpoint, 'vmlinuz'))
  867. init_path = os.path.join(mountpoint, 'init')
  868. with open(init_path, 'w') as f:
  869. f.write(init_script)
  870. os.chmod(init_path, 0o755)
  871. dracut_args = [
  872. '--kver', kernel_version,
  873. '--include', init_path,
  874. '/usr/lib/dracut/hooks/pre-pivot/initscript.sh',
  875. '--no-hostonly', '--nolvmconf', '--nomdadmconf',
  876. ]
  877. if extra_files:
  878. dracut_args += ['--install', ' '.join(extra_files)]
  879. subprocess.check_call(
  880. ['dracut'] + dracut_args + [os.path.join(mountpoint,
  881. 'initrd')],
  882. stderr=subprocess.DEVNULL
  883. )
  884. finally:
  885. subprocess.check_call(['sudo', 'umount', mountpoint])
  886. shutil.rmtree(mountpoint)
  887. subprocess.check_call(['sudo', 'losetup', '-d', loopdev])
  888. def create_local_file(self, filename, content, mode='w'):
  889. with open(filename, mode) as file:
  890. file.write(content)
  891. self.addCleanup(os.unlink, filename)
  892. def create_remote_file(self, vm, filename, content):
  893. self.loop.run_until_complete(vm.run_for_stdio(
  894. 'cat > {}'.format(shlex.quote(filename)),
  895. user='root', input=content.encode('utf-8')))
  896. @asyncio.coroutine
  897. def wait_for_session(self, vm):
  898. yield from asyncio.wait_for(
  899. vm.run_service_for_stdio(
  900. 'qubes.WaitForSession', input=vm.default_user.encode()),
  901. timeout=30)
  902. _templates = None
  903. def list_templates():
  904. '''Returns tuple of template names available in the system.'''
  905. global _templates
  906. if _templates is None:
  907. try:
  908. app = qubes.Qubes()
  909. _templates = tuple(vm.name for vm in app.domains
  910. if isinstance(vm, qubes.vm.templatevm.TemplateVM))
  911. app.close()
  912. del app
  913. except OSError:
  914. _templates = ()
  915. return _templates
  916. def extra_info(obj):
  917. '''Return short info identifying object.
  918. For example, if obj is a qube, return its name. This is for use with
  919. :py:mod:`objgraph` package.
  920. '''
  921. # Feel free to extend to other cases.
  922. if isinstance(obj, qubes.vm.qubesvm.QubesVM):
  923. try:
  924. return obj.name
  925. except AttributeError:
  926. pass
  927. if isinstance(obj, unittest.TestCase):
  928. return obj.id()
  929. return ''
  930. def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
  931. # discard any tests from this module, because it hosts base classes
  932. tests = unittest.TestSuite()
  933. for modname in (
  934. # unit tests
  935. 'qubes.tests.events',
  936. 'qubes.tests.devices',
  937. 'qubes.tests.devices_block',
  938. 'qubes.tests.firewall',
  939. 'qubes.tests.init',
  940. 'qubes.tests.vm.init',
  941. 'qubes.tests.storage',
  942. 'qubes.tests.storage_file',
  943. 'qubes.tests.storage_lvm',
  944. 'qubes.tests.storage_kernels',
  945. 'qubes.tests.ext',
  946. 'qubes.tests.vm.qubesvm',
  947. 'qubes.tests.vm.mix.net',
  948. 'qubes.tests.vm.adminvm',
  949. 'qubes.tests.vm.appvm',
  950. 'qubes.tests.vm.dispvm',
  951. 'qubes.tests.app',
  952. 'qubes.tests.tarwriter',
  953. 'qubes.tests.api',
  954. 'qubes.tests.api_admin',
  955. 'qubes.tests.api_misc',
  956. 'qubespolicy.tests',
  957. 'qubespolicy.tests.cli',
  958. ):
  959. tests.addTests(loader.loadTestsFromName(modname))
  960. # GTK/Glib is way too old there
  961. if 'TRAVIS' not in os.environ:
  962. for modname in (
  963. 'qubespolicy.tests.gtkhelpers',
  964. 'qubespolicy.tests.rpcconfirmation',
  965. ):
  966. tests.addTests(loader.loadTestsFromName(modname))
  967. tests.addTests(loader.discover(
  968. os.path.join(os.path.dirname(__file__), 'tools')))
  969. if not in_dom0:
  970. return tests
  971. for modname in (
  972. # integration tests
  973. 'qubes.tests.integ.basic',
  974. 'qubes.tests.integ.storage',
  975. 'qubes.tests.integ.devices_pci',
  976. 'qubes.tests.integ.dom0_update',
  977. 'qubes.tests.integ.network',
  978. 'qubes.tests.integ.dispvm',
  979. 'qubes.tests.integ.vm_qrexec_gui',
  980. 'qubes.tests.integ.backup',
  981. 'qubes.tests.integ.backupcompatibility',
  982. # 'qubes.tests.regressions',
  983. # external modules
  984. # 'qubes.tests.extra',
  985. ):
  986. tests.addTests(loader.loadTestsFromName(modname))
  987. return tests