__init__.py 35 KB

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