__init__.py 33 KB

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