__init__.py 35 KB

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