__init__.py 35 KB

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