__init__.py 36 KB

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