__init__.py 33 KB

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