__init__.py 36 KB

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