qubesvm.py 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051
  1. # pylint: disable=protected-access
  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 Wojtek Porczyk <woju@invisiblethingslab.com>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. #
  21. import base64
  22. import os
  23. import subprocess
  24. import tempfile
  25. import unittest
  26. import uuid
  27. import datetime
  28. import asyncio
  29. import functools
  30. import lxml.etree
  31. import unittest.mock
  32. import shutil
  33. import qubes
  34. import qubes.exc
  35. import qubes.config
  36. import qubes.devices
  37. import qubes.vm
  38. import qubes.vm.qubesvm
  39. import qubes.tests
  40. import qubes.tests.vm
  41. class TestApp(object):
  42. labels = {1: qubes.Label(1, '0xcc0000', 'red')}
  43. def __init__(self):
  44. self.domains = {}
  45. self.host = unittest.mock.Mock()
  46. self.host.memory_total = 4096 * 1024
  47. class TestFeatures(dict):
  48. def __init__(self, vm, **kwargs) -> None:
  49. self.vm = vm
  50. super().__init__(**kwargs)
  51. def check_with_template(self, feature, default):
  52. vm = self.vm
  53. while vm is not None:
  54. try:
  55. return vm.features[feature]
  56. except KeyError:
  57. vm = getattr(vm, 'template', None)
  58. return default
  59. class TestProp(object):
  60. # pylint: disable=too-few-public-methods
  61. __name__ = 'testprop'
  62. class TestDeviceCollection(object):
  63. def __init__(self):
  64. self._list = []
  65. def persistent(self):
  66. return self._list
  67. class TestQubesDB(object):
  68. def __init__(self, data=None):
  69. self.data = {}
  70. if data:
  71. self.data = data
  72. def write(self, path, value):
  73. self.data[path] = value
  74. def rm(self, path):
  75. if path.endswith('/'):
  76. for key in [x for x in self.data if x.startswith(path)]:
  77. del self.data[key]
  78. else:
  79. self.data.pop(path, None)
  80. def list(self, prefix):
  81. return [key for key in self.data if key.startswith(prefix)]
  82. def close(self):
  83. pass
  84. class TestVM(object):
  85. # pylint: disable=too-few-public-methods
  86. app = TestApp()
  87. def __init__(self, **kwargs):
  88. self.running = False
  89. self.installed_by_rpm = False
  90. for k, v in kwargs.items():
  91. setattr(self, k, v)
  92. self.devices = {'pci': TestDeviceCollection()}
  93. self.features = TestFeatures(self)
  94. def is_running(self):
  95. return self.running
  96. class TC_00_setters(qubes.tests.QubesTestCase):
  97. def setUp(self):
  98. super().setUp()
  99. self.vm = TestVM()
  100. self.prop = TestProp()
  101. def test_000_setter_qid(self):
  102. self.assertEqual(
  103. qubes.vm._setter_qid(self.vm, self.prop, 5), 5)
  104. def test_001_setter_qid_lt_0(self):
  105. with self.assertRaises(ValueError):
  106. qubes.vm._setter_qid(self.vm, self.prop, -1)
  107. def test_002_setter_qid_gt_max(self):
  108. with self.assertRaises(ValueError):
  109. qubes.vm._setter_qid(self.vm,
  110. self.prop, qubes.config.max_qid + 5)
  111. @unittest.skip('test not implemented')
  112. def test_020_setter_kernel(self):
  113. pass
  114. def test_030_setter_label_object(self):
  115. label = TestApp.labels[1]
  116. self.assertIs(label,
  117. qubes.vm.setter_label(self.vm, self.prop, label))
  118. def test_031_setter_label_getitem(self):
  119. label = TestApp.labels[1]
  120. self.assertIs(label,
  121. qubes.vm.setter_label(self.vm, self.prop, 'label-1'))
  122. # there is no check for self.app.get_label()
  123. def test_040_setter_virt_mode(self):
  124. self.assertEqual(
  125. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'hvm'),
  126. 'hvm')
  127. self.assertEqual(
  128. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'HVM'),
  129. 'hvm')
  130. self.assertEqual(
  131. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'PV'),
  132. 'pv')
  133. self.assertEqual(
  134. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'pvh'),
  135. 'pvh')
  136. self.vm.devices['pci']._list.append(object())
  137. with self.assertRaises(ValueError):
  138. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'pvh')
  139. with self.assertRaises(ValueError):
  140. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'True')
  141. class TC_10_default(qubes.tests.QubesTestCase):
  142. def setUp(self):
  143. super().setUp()
  144. self.app = TestApp()
  145. self.vm = TestVM(app=self.app)
  146. self.prop = TestProp()
  147. def test_000_default_with_template_simple(self):
  148. default_getter = qubes.vm.qubesvm._default_with_template('kernel',
  149. 'dfl-kernel')
  150. self.assertEqual(default_getter(self.vm), 'dfl-kernel')
  151. self.vm.template = None
  152. self.assertEqual(default_getter(self.vm), 'dfl-kernel')
  153. self.vm.template = unittest.mock.Mock()
  154. self.vm.template.kernel = 'template-kernel'
  155. self.assertEqual(default_getter(self.vm), 'template-kernel')
  156. def test_001_default_with_template_callable(self):
  157. default_getter = qubes.vm.qubesvm._default_with_template('kernel',
  158. lambda x: x.app.default_kernel)
  159. self.app.default_kernel = 'global-dfl-kernel'
  160. self.assertEqual(default_getter(self.vm), 'global-dfl-kernel')
  161. self.vm.template = None
  162. self.assertEqual(default_getter(self.vm), 'global-dfl-kernel')
  163. self.vm.template = unittest.mock.Mock()
  164. self.vm.template.kernel = 'template-kernel'
  165. self.assertEqual(default_getter(self.vm), 'template-kernel')
  166. def test_010_default_virt_mode(self):
  167. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  168. 'pvh')
  169. self.vm.template = unittest.mock.Mock()
  170. self.vm.template.virt_mode = 'hvm'
  171. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  172. 'hvm')
  173. self.vm.template = None
  174. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  175. 'pvh')
  176. self.vm.devices['pci'].persistent().append('some-dev')
  177. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  178. 'hvm')
  179. def test_020_default_maxmem(self):
  180. default_maxmem = 2048
  181. self.vm.is_memory_balancing_possible = \
  182. lambda: qubes.vm.qubesvm.QubesVM.is_memory_balancing_possible(
  183. self.vm)
  184. self.vm.virt_mode = 'pvh'
  185. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm),
  186. default_maxmem)
  187. self.vm.virt_mode = 'hvm'
  188. # HVM without qubes tools
  189. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 0)
  190. # just 'qrexec' feature
  191. self.vm.features['qrexec'] = True
  192. print(self.vm.features.check_with_template('qrexec', False))
  193. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm),
  194. default_maxmem)
  195. # some supported-service.*, but not meminfo-writer
  196. self.vm.features['supported-service.qubes-firewall'] = True
  197. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 0)
  198. # then add meminfo-writer
  199. self.vm.features['supported-service.meminfo-writer'] = True
  200. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm),
  201. default_maxmem)
  202. def test_021_default_maxmem_with_pcidevs(self):
  203. self.vm.is_memory_balancing_possible = \
  204. lambda: qubes.vm.qubesvm.QubesVM.is_memory_balancing_possible(
  205. self.vm)
  206. self.vm.devices['pci'].persistent().append('00_00.0')
  207. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 0)
  208. def test_022_default_maxmem_linux(self):
  209. self.vm.is_memory_balancing_possible = \
  210. lambda: qubes.vm.qubesvm.QubesVM.is_memory_balancing_possible(
  211. self.vm)
  212. self.vm.virt_mode = 'pvh'
  213. self.vm.memory = 400
  214. self.vm.features['os'] = 'Linux'
  215. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 2048)
  216. self.vm.memory = 100
  217. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 1000)
  218. class QubesVMTestsMixin(object):
  219. property_no_default = object()
  220. def setUp(self):
  221. super(QubesVMTestsMixin, self).setUp()
  222. self.app = qubes.tests.vm.TestApp()
  223. self.app.vmm.offline_mode = True
  224. self.app.default_kernel = None
  225. # when full test run is called, extensions are loaded by earlier
  226. # tests, but if just this test class is run, load them manually here,
  227. # to have the same behaviour
  228. qubes.ext.get_extensions()
  229. def tearDown(self):
  230. try:
  231. # self.app is not a real events emiter, so make the call manually
  232. for handler in qubes.Qubes.__handlers__.get('qubes-close'):
  233. handler(self.app, 'qubes-close')
  234. self.app.domains.close()
  235. except AttributeError:
  236. pass
  237. super(QubesVMTestsMixin, self).tearDown()
  238. def get_vm(self, name='test', cls=qubes.vm.qubesvm.QubesVM, vm=None, **kwargs):
  239. if not vm:
  240. vm = cls(self.app, None,
  241. qid=kwargs.pop('qid', 1), name=qubes.tests.VMPREFIX + name,
  242. **kwargs)
  243. self.app.domains[vm.qid] = vm
  244. self.app.domains[vm.uuid] = vm
  245. self.app.domains[vm.name] = vm
  246. self.app.domains[vm] = vm
  247. self.addCleanup(vm.close)
  248. return vm
  249. def assertPropertyValue(self, vm, prop_name, set_value, expected_value,
  250. expected_xml_content=None):
  251. # FIXME: any better exception list? or maybe all of that should be a
  252. # single exception?
  253. with self.assertNotRaises((ValueError, TypeError, KeyError)):
  254. setattr(vm, prop_name, set_value)
  255. self.assertEqual(getattr(vm, prop_name), expected_value)
  256. if expected_xml_content is not None:
  257. xml = vm.__xml__()
  258. prop_xml = xml.xpath(
  259. './properties/property[@name=\'{}\']'.format(prop_name))
  260. self.assertEqual(len(prop_xml), 1, "Property not found in XML")
  261. self.assertEqual(prop_xml[0].text, expected_xml_content)
  262. def assertPropertyInvalidValue(self, vm, prop_name, set_value):
  263. orig_value_set = True
  264. orig_value = None
  265. try:
  266. orig_value = getattr(vm, prop_name)
  267. except AttributeError:
  268. orig_value_set = False
  269. # FIXME: any better exception list? or maybe all of that should be a
  270. # single exception?
  271. with self.assertRaises((ValueError, TypeError, KeyError)):
  272. setattr(vm, prop_name, set_value)
  273. if orig_value_set:
  274. self.assertEqual(getattr(vm, prop_name), orig_value)
  275. else:
  276. with self.assertRaises(AttributeError):
  277. getattr(vm, prop_name)
  278. def assertPropertyDefaultValue(self, vm, prop_name,
  279. expected_default=property_no_default):
  280. if expected_default is self.property_no_default:
  281. with self.assertRaises(AttributeError):
  282. getattr(vm, prop_name)
  283. else:
  284. with self.assertNotRaises(AttributeError):
  285. self.assertEqual(getattr(vm, prop_name), expected_default)
  286. xml = vm.__xml__()
  287. prop_xml = xml.xpath(
  288. './properties/property[@name=\'{}\']'.format(prop_name))
  289. self.assertEqual(len(prop_xml), 0, "Property still found in XML")
  290. def _test_generic_bool_property(self, vm, prop_name, default=False):
  291. self.assertPropertyDefaultValue(vm, prop_name, default)
  292. self.assertPropertyValue(vm, prop_name, False, False, 'False')
  293. self.assertPropertyValue(vm, prop_name, True, True, 'True')
  294. delattr(vm, prop_name)
  295. self.assertPropertyDefaultValue(vm, prop_name, default)
  296. self.assertPropertyValue(vm, prop_name, 'True', True, 'True')
  297. self.assertPropertyValue(vm, prop_name, 'False', False, 'False')
  298. self.assertPropertyInvalidValue(vm, prop_name, 'xxx')
  299. self.assertPropertyValue(vm, prop_name, 123, True)
  300. self.assertPropertyInvalidValue(vm, prop_name, '')
  301. class TC_90_QubesVM(QubesVMTestsMixin, qubes.tests.QubesTestCase):
  302. def test_000_init(self):
  303. self.get_vm()
  304. def test_001_init_no_qid_or_name(self):
  305. with self.assertRaises(AssertionError):
  306. qubes.vm.qubesvm.QubesVM(self.app, None,
  307. name=qubes.tests.VMPREFIX + 'test')
  308. with self.assertRaises(AssertionError):
  309. qubes.vm.qubesvm.QubesVM(self.app, None,
  310. qid=1)
  311. def test_003_init_fire_domain_init(self):
  312. class TestVM2(qubes.vm.qubesvm.QubesVM):
  313. event_fired = False
  314. @qubes.events.handler('domain-init')
  315. def on_domain_init(self, event): # pylint: disable=unused-argument
  316. self.__class__.event_fired = True
  317. TestVM2(self.app, None, qid=1, name=qubes.tests.VMPREFIX + 'test')
  318. self.assertTrue(TestVM2.event_fired)
  319. def test_004_uuid_autogen(self):
  320. vm = self.get_vm()
  321. self.assertTrue(hasattr(vm, 'uuid'))
  322. def test_100_qid(self):
  323. vm = self.get_vm()
  324. self.assertIsInstance(vm.qid, int)
  325. with self.assertRaises(AttributeError):
  326. vm.qid = 2
  327. def test_110_name(self):
  328. vm = self.get_vm()
  329. self.assertIsInstance(vm.name, str)
  330. def test_120_uuid(self):
  331. my_uuid = uuid.uuid4()
  332. vm = self.get_vm(uuid=my_uuid)
  333. self.assertIsInstance(vm.uuid, uuid.UUID)
  334. self.assertIs(vm.uuid, my_uuid)
  335. with self.assertRaises(AttributeError):
  336. vm.uuid = uuid.uuid4()
  337. @unittest.skip('TODO: how to not fail on making an icon symlink here?')
  338. def test_130_label(self):
  339. vm = self.get_vm()
  340. self.assertPropertyDefaultValue(vm, 'label')
  341. self.assertPropertyValue(vm, 'label', self.app.labels[1],
  342. self.app.labels[1], 'label-1')
  343. del vm.label
  344. self.assertPropertyDefaultValue(vm, 'label')
  345. self.assertPropertyValue(vm, 'label', 'red',
  346. self.app.labels[1], 'label-1')
  347. self.assertPropertyValue(vm, 'label', 'label-1',
  348. self.app.labels[1], 'label-1')
  349. def test_131_label_invalid(self):
  350. vm = self.get_vm()
  351. self.assertPropertyInvalidValue(vm, 'label', 'invalid')
  352. self.assertPropertyInvalidValue(vm, 'label', 123)
  353. def test_160_memory(self):
  354. vm = self.get_vm()
  355. self.assertPropertyDefaultValue(vm, 'memory', 400)
  356. self.assertPropertyValue(vm, 'memory', 500, 500, '500')
  357. del vm.memory
  358. self.assertPropertyDefaultValue(vm, 'memory', 400)
  359. self.assertPropertyValue(vm, 'memory', '500', 500, '500')
  360. def test_161_memory_invalid(self):
  361. vm = self.get_vm()
  362. self.assertPropertyInvalidValue(vm, 'memory', -100)
  363. self.assertPropertyInvalidValue(vm, 'memory', '-100')
  364. self.assertPropertyInvalidValue(vm, 'memory', '')
  365. # TODO: higher than maxmem
  366. # TODO: human readable setter (500M, 4G)?
  367. def test_170_maxmem(self):
  368. vm = self.get_vm()
  369. self.assertPropertyDefaultValue(vm, 'maxmem',
  370. self.app.host.memory_total / 1024 / 2)
  371. self.assertPropertyValue(vm, 'maxmem', 500, 500, '500')
  372. del vm.maxmem
  373. self.assertPropertyDefaultValue(vm, 'maxmem',
  374. self.app.host.memory_total / 1024 / 2)
  375. self.assertPropertyValue(vm, 'maxmem', '500', 500, '500')
  376. def test_171_maxmem_invalid(self):
  377. vm = self.get_vm()
  378. self.assertPropertyInvalidValue(vm, 'maxmem', -100)
  379. self.assertPropertyInvalidValue(vm, 'maxmem', '-100')
  380. self.assertPropertyInvalidValue(vm, 'maxmem', '')
  381. # TODO: lower than memory
  382. # TODO: human readable setter (500M, 4G)?
  383. def test_190_vcpus(self):
  384. vm = self.get_vm()
  385. self.assertPropertyDefaultValue(vm, 'vcpus', 2)
  386. self.assertPropertyValue(vm, 'vcpus', 3, 3, '3')
  387. del vm.vcpus
  388. self.assertPropertyDefaultValue(vm, 'vcpus', 2)
  389. self.assertPropertyValue(vm, 'vcpus', '3', 3, '3')
  390. def test_191_vcpus_invalid(self):
  391. vm = self.get_vm()
  392. self.assertPropertyInvalidValue(vm, 'vcpus', 0)
  393. self.assertPropertyInvalidValue(vm, 'vcpus', -2)
  394. self.assertPropertyInvalidValue(vm, 'vcpus', '-2')
  395. self.assertPropertyInvalidValue(vm, 'vcpus', '')
  396. def test_200_debug(self):
  397. vm = self.get_vm()
  398. self._test_generic_bool_property(vm, 'debug', False)
  399. def test_210_installed_by_rpm(self):
  400. vm = self.get_vm()
  401. self._test_generic_bool_property(vm, 'installed_by_rpm', False)
  402. def test_220_include_in_backups(self):
  403. vm = self.get_vm()
  404. self._test_generic_bool_property(vm, 'include_in_backups', True)
  405. @qubes.tests.skipUnlessDom0
  406. def test_250_kernel(self):
  407. kernels = os.listdir(os.path.join(
  408. qubes.config.qubes_base_dir,
  409. qubes.config.system_path['qubes_kernels_base_dir']))
  410. if not len(kernels):
  411. self.skipTest('Needs at least one kernel installed')
  412. self.app.default_kernel = kernels[0]
  413. vm = self.get_vm()
  414. self.assertPropertyDefaultValue(vm, 'kernel', kernels[0])
  415. self.assertPropertyValue(vm, 'kernel', kernels[-1], kernels[-1],
  416. kernels[-1])
  417. del vm.kernel
  418. self.assertPropertyDefaultValue(vm, 'kernel', kernels[0])
  419. @qubes.tests.skipUnlessDom0
  420. def test_251_kernel_invalid(self):
  421. vm = self.get_vm()
  422. self.assertPropertyInvalidValue(vm, 'kernel', 123)
  423. self.assertPropertyInvalidValue(vm, 'kernel', 'invalid')
  424. def test_252_kernel_empty(self):
  425. vm = self.get_vm()
  426. self.assertPropertyValue(vm, 'kernel', '', '', '')
  427. self.assertPropertyValue(vm, 'kernel', None, '', '')
  428. @unittest.mock.patch.dict(qubes.config.system_path,
  429. {'qubes_kernels_base_dir': '/tmp'})
  430. def test_260_kernelopts(self):
  431. d = tempfile.mkdtemp(prefix='/tmp/')
  432. self.addCleanup(shutil.rmtree, d)
  433. open(d + '/vmlinuz', 'w').close()
  434. open(d + '/initramfs', 'w').close()
  435. vm = self.get_vm()
  436. vm.kernel = os.path.basename(d)
  437. self.assertPropertyDefaultValue(vm, 'kernelopts',
  438. qubes.config.defaults['kernelopts'])
  439. self.assertPropertyValue(vm, 'kernelopts', 'some options',
  440. 'some options', 'some options')
  441. del vm.kernelopts
  442. self.assertPropertyDefaultValue(vm, 'kernelopts',
  443. qubes.config.defaults['kernelopts'])
  444. self.assertPropertyValue(vm, 'kernelopts', '',
  445. '', '')
  446. # TODO?
  447. # self.assertPropertyInvalidValue(vm, 'kernelopts', None),
  448. @unittest.skip('test not implemented')
  449. def test_261_kernelopts_pcidevs(self):
  450. vm = self.get_vm()
  451. # how to do that here? use dummy DeviceManager/DeviceCollection?
  452. # Disable events?
  453. vm.devices['pci'].attach('something')
  454. self.assertPropertyDefaultValue(vm, 'kernelopts',
  455. qubes.config.defaults['kernelopts_pcidevs'])
  456. @unittest.mock.patch.dict(qubes.config.system_path,
  457. {'qubes_kernels_base_dir': '/tmp'})
  458. def test_262_kernelopts(self):
  459. d = tempfile.mkdtemp(prefix='/tmp/')
  460. self.addCleanup(shutil.rmtree, d)
  461. open(d + '/vmlinuz', 'w').close()
  462. open(d + '/initramfs', 'w').close()
  463. with open(d + '/default-kernelopts-nopci.txt', 'w') as f:
  464. f.write('some default options')
  465. vm = self.get_vm()
  466. vm.kernel = os.path.basename(d)
  467. self.assertPropertyDefaultValue(vm, 'kernelopts',
  468. 'some default options')
  469. self.assertPropertyValue(vm, 'kernelopts', 'some options',
  470. 'some options', 'some options')
  471. del vm.kernelopts
  472. self.assertPropertyDefaultValue(vm, 'kernelopts',
  473. 'some default options')
  474. self.assertPropertyValue(vm, 'kernelopts', '',
  475. '', '')
  476. def test_270_qrexec_timeout(self):
  477. vm = self.get_vm()
  478. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 60)
  479. self.assertPropertyValue(vm, 'qrexec_timeout', 3, 3, '3')
  480. del vm.qrexec_timeout
  481. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 60)
  482. self.assertPropertyValue(vm, 'qrexec_timeout', '3', 3, '3')
  483. def test_271_qrexec_timeout_invalid(self):
  484. vm = self.get_vm()
  485. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', -2)
  486. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', '-2')
  487. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', '')
  488. def test_272_qrexec_timeout_global_changed(self):
  489. self.app.default_qrexec_timeout = 123
  490. vm = self.get_vm()
  491. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 123)
  492. self.assertPropertyValue(vm, 'qrexec_timeout', 3, 3, '3')
  493. del vm.qrexec_timeout
  494. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 123)
  495. self.assertPropertyValue(vm, 'qrexec_timeout', '3', 3, '3')
  496. def test_280_autostart(self):
  497. vm = self.get_vm()
  498. # FIXME any better idea to not involve systemctl call at this stage?
  499. vm.events_enabled = False
  500. self._test_generic_bool_property(vm, 'autostart', False)
  501. @qubes.tests.skipUnlessDom0
  502. def test_281_autostart_systemd(self):
  503. vm = self.get_vm()
  504. self.assertFalse(os.path.exists(
  505. '/etc/systemd/system/multi-user.target.wants/'
  506. 'qubes-vm@{}.service'.format(vm.name)),
  507. "systemd service enabled before setting autostart")
  508. vm.autostart = True
  509. self.assertTrue(os.path.exists(
  510. '/etc/systemd/system/multi-user.target.wants/'
  511. 'qubes-vm@{}.service'.format(vm.name)),
  512. "systemd service not enabled by autostart=True")
  513. vm.autostart = False
  514. self.assertFalse(os.path.exists(
  515. '/etc/systemd/system/multi-user.target.wants/'
  516. 'qubes-vm@{}.service'.format(vm.name)),
  517. "systemd service not disabled by autostart=False")
  518. vm.autostart = True
  519. del vm.autostart
  520. self.assertFalse(os.path.exists(
  521. '/etc/systemd/system/multi-user.target.wants/'
  522. 'qubes-vm@{}.service'.format(vm.name)),
  523. "systemd service not disabled by resetting autostart")
  524. def test_290_management_dispvm(self):
  525. vm = self.get_vm()
  526. vm2 = self.get_vm('test2', qid=2)
  527. self.app.management_dispvm = None
  528. self.assertPropertyDefaultValue(vm, 'management_dispvm', None)
  529. self.app.management_dispvm = vm
  530. try:
  531. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm)
  532. self.assertPropertyValue(vm, 'management_dispvm',
  533. 'test-inst-test2', vm2)
  534. finally:
  535. self.app.management_dispvm = None
  536. def test_291_management_dispvm_template_based(self):
  537. tpl = self.get_vm(name='tpl', cls=qubes.vm.templatevm.TemplateVM)
  538. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=tpl, qid=2)
  539. vm2 = self.get_vm('test2', qid=3)
  540. del vm.volumes
  541. self.app.management_dispvm = None
  542. try:
  543. self.assertPropertyDefaultValue(vm, 'management_dispvm', None)
  544. self.app.management_dispvm = vm
  545. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm)
  546. tpl.management_dispvm = vm2
  547. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm2)
  548. self.assertPropertyValue(vm, 'management_dispvm',
  549. 'test-inst-test2', vm2)
  550. finally:
  551. self.app.management_dispvm = None
  552. @unittest.skip('TODO')
  553. def test_320_seamless_gui_mode(self):
  554. vm = self.get_vm()
  555. self._test_generic_bool_property(vm, 'seamless_gui_mode')
  556. # TODO: reject setting to True when guiagent_installed is false
  557. def test_330_mac(self):
  558. vm = self.get_vm()
  559. # TODO: calculate proper default here
  560. default_mac = vm.mac
  561. self.assertIsNotNone(default_mac)
  562. self.assertPropertyDefaultValue(vm, 'mac', default_mac)
  563. self.assertPropertyValue(vm, 'mac', '00:11:22:33:44:55',
  564. '00:11:22:33:44:55', '00:11:22:33:44:55')
  565. del vm.mac
  566. self.assertPropertyDefaultValue(vm, 'mac', default_mac)
  567. def test_331_mac_invalid(self):
  568. vm = self.get_vm()
  569. self.assertPropertyInvalidValue(vm, 'mac', 123)
  570. self.assertPropertyInvalidValue(vm, 'mac', 'invalid')
  571. self.assertPropertyInvalidValue(vm, 'mac', '00:11:22:33:44:55:66')
  572. def test_340_default_user(self):
  573. vm = self.get_vm()
  574. self.assertPropertyDefaultValue(vm, 'default_user', 'user')
  575. self.assertPropertyValue(vm, 'default_user', 'someuser', 'someuser',
  576. 'someuser')
  577. del vm.default_user
  578. self.assertPropertyDefaultValue(vm, 'default_user', 'user')
  579. self.assertPropertyValue(vm, 'default_user', 123, '123', '123')
  580. vm.default_user = 'user'
  581. # TODO: check propagation for template-based VMs
  582. @unittest.skip('TODO')
  583. def test_350_timezone(self):
  584. vm = self.get_vm()
  585. self.assertPropertyDefaultValue(vm, 'timezone', 'localtime')
  586. self.assertPropertyValue(vm, 'timezone', 0, 0, '0')
  587. del vm.timezone
  588. self.assertPropertyDefaultValue(vm, 'timezone', 'localtime')
  589. self.assertPropertyValue(vm, 'timezone', '0', 0, '0')
  590. self.assertPropertyValue(vm, 'timezone', -3600, -3600, '-3600')
  591. self.assertPropertyValue(vm, 'timezone', 7200, 7200, '7200')
  592. @unittest.skip('TODO')
  593. def test_350_timezone_invalid(self):
  594. vm = self.get_vm()
  595. self.assertPropertyInvalidValue(vm, 'timezone', 'xxx')
  596. @unittest.skip('TODO')
  597. def test_360_drive(self):
  598. vm = self.get_vm()
  599. self.assertPropertyDefaultValue(vm, 'drive', None)
  600. # self.execute_tests('drive', [
  601. # ('hd:dom0:/tmp/drive.img', 'hd:dom0:/tmp/drive.img', True),
  602. # ('hd:/tmp/drive.img', 'hd:dom0:/tmp/drive.img', True),
  603. # ('cdrom:dom0:/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  604. # ('cdrom:/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  605. # ('/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  606. # ('hd:drive.img', '', False),
  607. # ('drive.img', '', False),
  608. # ])
  609. def test_400_backup_timestamp(self):
  610. vm = self.get_vm()
  611. timestamp = datetime.datetime(2016, 1, 1, 12, 14, 2)
  612. timestamp_str = timestamp.strftime('%s')
  613. self.assertPropertyDefaultValue(vm, 'backup_timestamp', None)
  614. self.assertPropertyValue(vm, 'backup_timestamp', int(timestamp_str),
  615. int(timestamp_str), timestamp_str)
  616. del vm.backup_timestamp
  617. self.assertPropertyDefaultValue(vm, 'backup_timestamp', None)
  618. self.assertPropertyValue(vm, 'backup_timestamp', timestamp_str,
  619. int(timestamp_str))
  620. def test_401_backup_timestamp_invalid(self):
  621. vm = self.get_vm()
  622. self.assertPropertyInvalidValue(vm, 'backup_timestamp', 'xxx')
  623. self.assertPropertyInvalidValue(vm, 'backup_timestamp', None)
  624. def test_500_property_migrate_virt_mode(self):
  625. xml_template = '''
  626. <domain class="QubesVM" id="domain-1">
  627. <properties>
  628. <property name="qid">1</property>
  629. <property name="name">testvm</property>
  630. <property name="label" ref="label-1" />
  631. <property name="hvm">{hvm_value}</property>
  632. </properties>
  633. </domain>
  634. '''
  635. xml = lxml.etree.XML(xml_template.format(hvm_value='True'))
  636. vm = qubes.vm.qubesvm.QubesVM(self.app, xml)
  637. self.assertEqual(vm.virt_mode, 'hvm')
  638. with self.assertRaises(AttributeError):
  639. vm.hvm
  640. xml = lxml.etree.XML(xml_template.format(hvm_value='False'))
  641. vm = qubes.vm.qubesvm.QubesVM(self.app, xml)
  642. self.assertEqual(vm.virt_mode, 'pv')
  643. with self.assertRaises(AttributeError):
  644. vm.hvm
  645. def test_600_libvirt_xml_pv(self):
  646. expected = '''<domain type="xen">
  647. <name>test-inst-test</name>
  648. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  649. <memory unit="MiB">500</memory>
  650. <currentMemory unit="MiB">400</currentMemory>
  651. <vcpu placement="static">2</vcpu>
  652. <os>
  653. <type arch="x86_64" machine="xenpv">linux</type>
  654. <kernel>/tmp/kernel/vmlinuz</kernel>
  655. <initrd>/tmp/kernel/initramfs</initrd>
  656. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  657. </os>
  658. <features>
  659. </features>
  660. <clock offset='utc' adjustment='reset'>
  661. <timer name="tsc" mode="native"/>
  662. </clock>
  663. <on_poweroff>destroy</on_poweroff>
  664. <on_reboot>destroy</on_reboot>
  665. <on_crash>destroy</on_crash>
  666. <devices>
  667. <disk type="block" device="disk">
  668. <driver name="phy" />
  669. <source dev="/tmp/kernel/modules.img" />
  670. <target dev="xvdd" />
  671. <backenddomain name="dom0" />
  672. </disk>
  673. <console type="pty">
  674. <target type="xen" port="0"/>
  675. </console>
  676. </devices>
  677. </domain>
  678. '''
  679. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  680. vm = self.get_vm(uuid=my_uuid)
  681. vm.netvm = None
  682. vm.virt_mode = 'pv'
  683. with unittest.mock.patch('qubes.config.qubes_base_dir',
  684. '/tmp/qubes-test'):
  685. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  686. os.makedirs(kernel_dir, exist_ok=True)
  687. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  688. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  689. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  690. vm.kernel = 'dummy'
  691. # tests for storage are later
  692. vm.volumes['kernel'] = unittest.mock.Mock(**{
  693. 'kernels_dir': '/tmp/kernel',
  694. 'block_device.return_value.domain': 'dom0',
  695. 'block_device.return_value.script': None,
  696. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  697. 'block_device.return_value.devtype': 'disk',
  698. 'block_device.return_value.name': 'kernel',
  699. })
  700. libvirt_xml = vm.create_config_file()
  701. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  702. lxml.etree.XML(expected))
  703. def test_600_libvirt_xml_hvm(self):
  704. expected = '''<domain type="xen">
  705. <name>test-inst-test</name>
  706. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  707. <memory unit="MiB">400</memory>
  708. <currentMemory unit="MiB">400</currentMemory>
  709. <vcpu placement="static">2</vcpu>
  710. <cpu mode='host-passthrough'>
  711. <!-- disable nested HVM -->
  712. <feature name='vmx' policy='disable'/>
  713. <feature name='svm' policy='disable'/>
  714. <!-- disable SMAP inside VM, because of Linux bug -->
  715. <feature name='smap' policy='disable'/>
  716. </cpu>
  717. <os>
  718. <type arch="x86_64" machine="xenfv">hvm</type>
  719. <!--
  720. For the libxl backend libvirt switches between OVMF (UEFI)
  721. and SeaBIOS based on the loader type. This has nothing to
  722. do with the hvmloader binary.
  723. -->
  724. <loader type="rom">hvmloader</loader>
  725. <boot dev="cdrom" />
  726. <boot dev="hd" />
  727. </os>
  728. <features>
  729. <pae/>
  730. <acpi/>
  731. <apic/>
  732. <viridian/>
  733. </features>
  734. <clock offset="variable" adjustment="0" basis="localtime" />
  735. <on_poweroff>destroy</on_poweroff>
  736. <on_reboot>destroy</on_reboot>
  737. <on_crash>destroy</on_crash>
  738. <devices>
  739. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  740. <emulator type="stubdom-linux" />
  741. <input type="tablet" bus="usb"/>
  742. <video>
  743. <model type="vga"/>
  744. </video>
  745. <graphics type="qubes"/>
  746. <console type="pty">
  747. <target type="xen" port="0"/>
  748. </console>
  749. </devices>
  750. </domain>
  751. '''
  752. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  753. vm = self.get_vm(uuid=my_uuid)
  754. vm.netvm = None
  755. vm.virt_mode = 'hvm'
  756. libvirt_xml = vm.create_config_file()
  757. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  758. lxml.etree.XML(expected))
  759. def test_600_libvirt_xml_hvm_dom0_kernel(self):
  760. expected = '''<domain type="xen">
  761. <name>test-inst-test</name>
  762. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  763. <memory unit="MiB">500</memory>
  764. <currentMemory unit="MiB">400</currentMemory>
  765. <vcpu placement="static">2</vcpu>
  766. <cpu mode='host-passthrough'>
  767. <!-- disable nested HVM -->
  768. <feature name='vmx' policy='disable'/>
  769. <feature name='svm' policy='disable'/>
  770. <!-- disable SMAP inside VM, because of Linux bug -->
  771. <feature name='smap' policy='disable'/>
  772. </cpu>
  773. <os>
  774. <type arch="x86_64" machine="xenfv">hvm</type>
  775. <!--
  776. For the libxl backend libvirt switches between OVMF (UEFI)
  777. and SeaBIOS based on the loader type. This has nothing to
  778. do with the hvmloader binary.
  779. -->
  780. <loader type="rom">hvmloader</loader>
  781. <boot dev="cdrom" />
  782. <boot dev="hd" />
  783. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  784. </os>
  785. <features>
  786. <pae/>
  787. <acpi/>
  788. <apic/>
  789. <viridian/>
  790. </features>
  791. <clock offset="variable" adjustment="0" basis="localtime" />
  792. <on_poweroff>destroy</on_poweroff>
  793. <on_reboot>destroy</on_reboot>
  794. <on_crash>destroy</on_crash>
  795. <devices>
  796. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  797. <emulator type="stubdom-linux" />
  798. <input type="tablet" bus="usb"/>
  799. <video>
  800. <model type="vga"/>
  801. </video>
  802. <graphics type="qubes"/>
  803. <console type="pty">
  804. <target type="xen" port="0"/>
  805. </console>
  806. </devices>
  807. </domain>
  808. '''
  809. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  810. vm = self.get_vm(uuid=my_uuid)
  811. vm.netvm = None
  812. vm.virt_mode = 'hvm'
  813. vm.features['qrexec'] = True
  814. with unittest.mock.patch('qubes.config.qubes_base_dir',
  815. '/tmp/qubes-test'):
  816. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  817. os.makedirs(kernel_dir, exist_ok=True)
  818. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  819. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  820. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  821. vm.kernel = 'dummy'
  822. libvirt_xml = vm.create_config_file()
  823. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  824. lxml.etree.XML(expected))
  825. def test_600_libvirt_xml_hvm_dom0_kernel_kernelopts(self):
  826. expected = '''<domain type="xen">
  827. <name>test-inst-test</name>
  828. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  829. <memory unit="MiB">500</memory>
  830. <currentMemory unit="MiB">400</currentMemory>
  831. <vcpu placement="static">2</vcpu>
  832. <cpu mode='host-passthrough'>
  833. <!-- disable nested HVM -->
  834. <feature name='vmx' policy='disable'/>
  835. <feature name='svm' policy='disable'/>
  836. <!-- disable SMAP inside VM, because of Linux bug -->
  837. <feature name='smap' policy='disable'/>
  838. </cpu>
  839. <os>
  840. <type arch="x86_64" machine="xenfv">hvm</type>
  841. <!--
  842. For the libxl backend libvirt switches between OVMF (UEFI)
  843. and SeaBIOS based on the loader type. This has nothing to
  844. do with the hvmloader binary.
  845. -->
  846. <loader type="rom">hvmloader</loader>
  847. <boot dev="cdrom" />
  848. <boot dev="hd" />
  849. <cmdline>kernel specific options nopat</cmdline>
  850. </os>
  851. <features>
  852. <pae/>
  853. <acpi/>
  854. <apic/>
  855. <viridian/>
  856. </features>
  857. <clock offset="variable" adjustment="0" basis="localtime" />
  858. <on_poweroff>destroy</on_poweroff>
  859. <on_reboot>destroy</on_reboot>
  860. <on_crash>destroy</on_crash>
  861. <devices>
  862. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  863. <emulator type="stubdom-linux" />
  864. <input type="tablet" bus="usb"/>
  865. <video>
  866. <model type="vga"/>
  867. </video>
  868. <graphics type="qubes"/>
  869. <console type="pty">
  870. <target type="xen" port="0"/>
  871. </console>
  872. </devices>
  873. </domain>
  874. '''
  875. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  876. vm = self.get_vm(uuid=my_uuid)
  877. vm.netvm = None
  878. vm.virt_mode = 'hvm'
  879. vm.features['qrexec'] = True
  880. with unittest.mock.patch('qubes.config.qubes_base_dir',
  881. '/tmp/qubes-test'):
  882. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  883. os.makedirs(kernel_dir, exist_ok=True)
  884. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  885. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  886. with open(os.path.join(kernel_dir,
  887. 'default-kernelopts-common.txt'), 'w') as f:
  888. f.write('kernel specific options \n')
  889. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  890. vm.kernel = 'dummy'
  891. libvirt_xml = vm.create_config_file()
  892. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  893. lxml.etree.XML(expected))
  894. def test_600_libvirt_xml_pvh(self):
  895. expected = '''<domain type="xen">
  896. <name>test-inst-test</name>
  897. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  898. <memory unit="MiB">500</memory>
  899. <currentMemory unit="MiB">400</currentMemory>
  900. <vcpu placement="static">2</vcpu>
  901. <cpu mode='host-passthrough'>
  902. <!-- disable nested HVM -->
  903. <feature name='vmx' policy='disable'/>
  904. <feature name='svm' policy='disable'/>
  905. <!-- disable SMAP inside VM, because of Linux bug -->
  906. <feature name='smap' policy='disable'/>
  907. </cpu>
  908. <os>
  909. <type arch="x86_64" machine="xenpvh">xenpvh</type>
  910. <kernel>/tmp/kernel/vmlinuz</kernel>
  911. <initrd>/tmp/kernel/initramfs</initrd>
  912. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  913. </os>
  914. <features>
  915. <pae/>
  916. <acpi/>
  917. <apic/>
  918. <viridian/>
  919. </features>
  920. <clock offset='utc' adjustment='reset'>
  921. <timer name="tsc" mode="native"/>
  922. </clock>
  923. <on_poweroff>destroy</on_poweroff>
  924. <on_reboot>destroy</on_reboot>
  925. <on_crash>destroy</on_crash>
  926. <devices>
  927. <disk type="block" device="disk">
  928. <driver name="phy" />
  929. <source dev="/tmp/kernel/modules.img" />
  930. <target dev="xvdd" />
  931. <backenddomain name="dom0" />
  932. </disk>
  933. <console type="pty">
  934. <target type="xen" port="0"/>
  935. </console>
  936. </devices>
  937. </domain>
  938. '''
  939. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  940. vm = self.get_vm(uuid=my_uuid)
  941. vm.netvm = None
  942. vm.virt_mode = 'pvh'
  943. with unittest.mock.patch('qubes.config.qubes_base_dir',
  944. '/tmp/qubes-test'):
  945. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  946. os.makedirs(kernel_dir, exist_ok=True)
  947. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  948. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  949. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  950. vm.kernel = 'dummy'
  951. # tests for storage are later
  952. vm.volumes['kernel'] = unittest.mock.Mock(**{
  953. 'kernels_dir': '/tmp/kernel',
  954. 'block_device.return_value.domain': 'dom0',
  955. 'block_device.return_value.script': None,
  956. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  957. 'block_device.return_value.devtype': 'disk',
  958. 'block_device.return_value.name': 'kernel',
  959. })
  960. libvirt_xml = vm.create_config_file()
  961. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  962. lxml.etree.XML(expected))
  963. def test_600_libvirt_xml_pvh_no_membalance(self):
  964. expected = '''<domain type="xen">
  965. <name>test-inst-test</name>
  966. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  967. <memory unit="MiB">400</memory>
  968. <currentMemory unit="MiB">400</currentMemory>
  969. <vcpu placement="static">2</vcpu>
  970. <cpu mode='host-passthrough'>
  971. <!-- disable nested HVM -->
  972. <feature name='vmx' policy='disable'/>
  973. <feature name='svm' policy='disable'/>
  974. <!-- disable SMAP inside VM, because of Linux bug -->
  975. <feature name='smap' policy='disable'/>
  976. </cpu>
  977. <os>
  978. <type arch="x86_64" machine="xenpvh">xenpvh</type>
  979. <kernel>/tmp/kernel/vmlinuz</kernel>
  980. <initrd>/tmp/kernel/initramfs</initrd>
  981. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  982. </os>
  983. <features>
  984. <pae/>
  985. <acpi/>
  986. <apic/>
  987. <viridian/>
  988. </features>
  989. <clock offset='utc' adjustment='reset'>
  990. <timer name="tsc" mode="native"/>
  991. </clock>
  992. <on_poweroff>destroy</on_poweroff>
  993. <on_reboot>destroy</on_reboot>
  994. <on_crash>destroy</on_crash>
  995. <devices>
  996. <disk type="block" device="disk">
  997. <driver name="phy" />
  998. <source dev="/tmp/kernel/modules.img" />
  999. <target dev="xvdd" />
  1000. <backenddomain name="dom0" />
  1001. </disk>
  1002. <console type="pty">
  1003. <target type="xen" port="0"/>
  1004. </console>
  1005. </devices>
  1006. </domain>
  1007. '''
  1008. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1009. vm = self.get_vm(uuid=my_uuid)
  1010. vm.netvm = None
  1011. vm.virt_mode = 'pvh'
  1012. vm.maxmem = 0
  1013. with unittest.mock.patch('qubes.config.qubes_base_dir',
  1014. '/tmp/qubes-test'):
  1015. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  1016. os.makedirs(kernel_dir, exist_ok=True)
  1017. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  1018. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  1019. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  1020. vm.kernel = 'dummy'
  1021. # tests for storage are later
  1022. vm.volumes['kernel'] = unittest.mock.Mock(**{
  1023. 'kernels_dir': '/tmp/kernel',
  1024. 'block_device.return_value.domain': 'dom0',
  1025. 'block_device.return_value.script': None,
  1026. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  1027. 'block_device.return_value.devtype': 'disk',
  1028. 'block_device.return_value.name': 'kernel',
  1029. })
  1030. libvirt_xml = vm.create_config_file()
  1031. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1032. lxml.etree.XML(expected))
  1033. def test_600_libvirt_xml_hvm_pcidev(self):
  1034. expected = '''<domain type="xen">
  1035. <name>test-inst-test</name>
  1036. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1037. <memory unit="MiB">400</memory>
  1038. <currentMemory unit="MiB">400</currentMemory>
  1039. <vcpu placement="static">2</vcpu>
  1040. <cpu mode='host-passthrough'>
  1041. <!-- disable nested HVM -->
  1042. <feature name='vmx' policy='disable'/>
  1043. <feature name='svm' policy='disable'/>
  1044. <!-- disable SMAP inside VM, because of Linux bug -->
  1045. <feature name='smap' policy='disable'/>
  1046. </cpu>
  1047. <os>
  1048. <type arch="x86_64" machine="xenfv">hvm</type>
  1049. <!--
  1050. For the libxl backend libvirt switches between OVMF (UEFI)
  1051. and SeaBIOS based on the loader type. This has nothing to
  1052. do with the hvmloader binary.
  1053. -->
  1054. <loader type="rom">hvmloader</loader>
  1055. <boot dev="cdrom" />
  1056. <boot dev="hd" />
  1057. </os>
  1058. <features>
  1059. <pae/>
  1060. <acpi/>
  1061. <apic/>
  1062. <viridian/>
  1063. <xen>
  1064. <e820_host state="on"/>
  1065. </xen>
  1066. </features>
  1067. <clock offset="variable" adjustment="0" basis="localtime" />
  1068. <on_poweroff>destroy</on_poweroff>
  1069. <on_reboot>destroy</on_reboot>
  1070. <on_crash>destroy</on_crash>
  1071. <devices>
  1072. <hostdev type="pci" managed="yes">
  1073. <source>
  1074. <address
  1075. bus="0x00"
  1076. slot="0x00"
  1077. function="0x0" />
  1078. </source>
  1079. </hostdev>
  1080. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1081. <emulator type="stubdom-linux" />
  1082. <input type="tablet" bus="usb"/>
  1083. <video>
  1084. <model type="vga"/>
  1085. </video>
  1086. <graphics type="qubes"/>
  1087. <console type="pty">
  1088. <target type="xen" port="0"/>
  1089. </console>
  1090. </devices>
  1091. </domain>
  1092. '''
  1093. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1094. # required for PCI devices listing
  1095. self.app.vmm.offline_mode = False
  1096. vm = self.get_vm(uuid=my_uuid)
  1097. vm.netvm = None
  1098. vm.virt_mode = 'hvm'
  1099. vm.kernel = None
  1100. # even with meminfo-writer enabled, should have memory==maxmem
  1101. vm.features['service.meminfo-writer'] = True
  1102. assignment = qubes.devices.DeviceAssignment(
  1103. vm, # this is violation of API, but for PCI the argument
  1104. # is unused
  1105. '00_00.0',
  1106. bus='pci',
  1107. persistent=True)
  1108. vm.devices['pci']._set.add(
  1109. assignment)
  1110. libvirt_xml = vm.create_config_file()
  1111. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1112. lxml.etree.XML(expected))
  1113. def test_600_libvirt_xml_hvm_cdrom_boot(self):
  1114. expected = '''<domain type="xen">
  1115. <name>test-inst-test</name>
  1116. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1117. <memory unit="MiB">400</memory>
  1118. <currentMemory unit="MiB">400</currentMemory>
  1119. <vcpu placement="static">2</vcpu>
  1120. <cpu mode='host-passthrough'>
  1121. <!-- disable nested HVM -->
  1122. <feature name='vmx' policy='disable'/>
  1123. <feature name='svm' policy='disable'/>
  1124. <!-- disable SMAP inside VM, because of Linux bug -->
  1125. <feature name='smap' policy='disable'/>
  1126. </cpu>
  1127. <os>
  1128. <type arch="x86_64" machine="xenfv">hvm</type>
  1129. <!--
  1130. For the libxl backend libvirt switches between OVMF (UEFI)
  1131. and SeaBIOS based on the loader type. This has nothing to
  1132. do with the hvmloader binary.
  1133. -->
  1134. <loader type="rom">hvmloader</loader>
  1135. <boot dev="cdrom" />
  1136. <boot dev="hd" />
  1137. </os>
  1138. <features>
  1139. <pae/>
  1140. <acpi/>
  1141. <apic/>
  1142. <viridian/>
  1143. </features>
  1144. <clock offset="variable" adjustment="0" basis="localtime" />
  1145. <on_poweroff>destroy</on_poweroff>
  1146. <on_reboot>destroy</on_reboot>
  1147. <on_crash>destroy</on_crash>
  1148. <devices>
  1149. <disk type="block" device="cdrom">
  1150. <driver name="phy" />
  1151. <source dev="/dev/sda" />
  1152. <!-- prefer xvdd for CDROM -->
  1153. <target dev="xvdd" />
  1154. <readonly/>
  1155. </disk>
  1156. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1157. <emulator type="stubdom-linux" />
  1158. <input type="tablet" bus="usb"/>
  1159. <video>
  1160. <model type="vga"/>
  1161. </video>
  1162. <graphics type="qubes"/>
  1163. <console type="pty">
  1164. <target type="xen" port="0"/>
  1165. </console>
  1166. </devices>
  1167. </domain>
  1168. '''
  1169. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1170. qdb = {
  1171. '/qubes-block-devices/sda': b'',
  1172. '/qubes-block-devices/sda/desc': b'Test device',
  1173. '/qubes-block-devices/sda/size': b'1024000',
  1174. '/qubes-block-devices/sda/mode': b'r',
  1175. }
  1176. test_qdb = TestQubesDB(qdb)
  1177. dom0 = qubes.vm.adminvm.AdminVM(self.app, None)
  1178. dom0._qdb_connection = test_qdb
  1179. self.get_vm('dom0', vm=dom0)
  1180. vm = self.get_vm(uuid=my_uuid)
  1181. vm.netvm = None
  1182. vm.virt_mode = 'hvm'
  1183. vm.kernel = None
  1184. dom0.events_enabled = True
  1185. self.app.vmm.offline_mode = False
  1186. dev = qubes.devices.DeviceAssignment(
  1187. dom0, 'sda',
  1188. {'devtype': 'cdrom', 'read-only': 'yes'}, persistent=True)
  1189. self.loop.run_until_complete(vm.devices['block'].attach(dev))
  1190. libvirt_xml = vm.create_config_file()
  1191. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1192. lxml.etree.XML(expected))
  1193. def test_600_libvirt_xml_hvm_cdrom_dom0_kernel_boot(self):
  1194. expected = '''<domain type="xen">
  1195. <name>test-inst-test</name>
  1196. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1197. <memory unit="MiB">400</memory>
  1198. <currentMemory unit="MiB">400</currentMemory>
  1199. <vcpu placement="static">2</vcpu>
  1200. <cpu mode='host-passthrough'>
  1201. <!-- disable nested HVM -->
  1202. <feature name='vmx' policy='disable'/>
  1203. <feature name='svm' policy='disable'/>
  1204. <!-- disable SMAP inside VM, because of Linux bug -->
  1205. <feature name='smap' policy='disable'/>
  1206. </cpu>
  1207. <os>
  1208. <type arch="x86_64" machine="xenfv">hvm</type>
  1209. <!--
  1210. For the libxl backend libvirt switches between OVMF (UEFI)
  1211. and SeaBIOS based on the loader type. This has nothing to
  1212. do with the hvmloader binary.
  1213. -->
  1214. <loader type="rom">hvmloader</loader>
  1215. <boot dev="cdrom" />
  1216. <boot dev="hd" />
  1217. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  1218. </os>
  1219. <features>
  1220. <pae/>
  1221. <acpi/>
  1222. <apic/>
  1223. <viridian/>
  1224. </features>
  1225. <clock offset="variable" adjustment="0" basis="localtime" />
  1226. <on_poweroff>destroy</on_poweroff>
  1227. <on_reboot>destroy</on_reboot>
  1228. <on_crash>destroy</on_crash>
  1229. <devices>
  1230. <disk type="block" device="disk">
  1231. <driver name="phy" />
  1232. <source dev="/tmp/kernel/modules.img" />
  1233. <target dev="xvdd" />
  1234. <backenddomain name="dom0" />
  1235. </disk>
  1236. <disk type="block" device="cdrom">
  1237. <driver name="phy" />
  1238. <source dev="/dev/sda" />
  1239. <target dev="xvdi" />
  1240. <readonly/>
  1241. </disk>
  1242. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1243. <emulator type="stubdom-linux" />
  1244. <input type="tablet" bus="usb"/>
  1245. <video>
  1246. <model type="vga"/>
  1247. </video>
  1248. <graphics type="qubes"/>
  1249. <console type="pty">
  1250. <target type="xen" port="0"/>
  1251. </console>
  1252. </devices>
  1253. </domain>
  1254. '''
  1255. qdb = {
  1256. '/qubes-block-devices/sda': b'',
  1257. '/qubes-block-devices/sda/desc': b'Test device',
  1258. '/qubes-block-devices/sda/size': b'1024000',
  1259. '/qubes-block-devices/sda/mode': b'r',
  1260. }
  1261. test_qdb = TestQubesDB(qdb)
  1262. dom0 = qubes.vm.adminvm.AdminVM(self.app, None)
  1263. dom0._qdb_connection = test_qdb
  1264. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1265. vm = self.get_vm(uuid=my_uuid)
  1266. vm.netvm = None
  1267. vm.virt_mode = 'hvm'
  1268. with unittest.mock.patch('qubes.config.qubes_base_dir',
  1269. '/tmp/qubes-test'):
  1270. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  1271. os.makedirs(kernel_dir, exist_ok=True)
  1272. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  1273. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  1274. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  1275. vm.kernel = 'dummy'
  1276. # tests for storage are later
  1277. vm.volumes['kernel'] = unittest.mock.Mock(**{
  1278. 'kernels_dir': '/tmp/kernel',
  1279. 'block_device.return_value.domain': 'dom0',
  1280. 'block_device.return_value.script': None,
  1281. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  1282. 'block_device.return_value.devtype': 'disk',
  1283. 'block_device.return_value.name': 'kernel',
  1284. })
  1285. dom0.events_enabled = True
  1286. self.app.vmm.offline_mode = False
  1287. dev = qubes.devices.DeviceAssignment(
  1288. dom0, 'sda',
  1289. {'devtype': 'cdrom', 'read-only': 'yes'}, persistent=True)
  1290. self.loop.run_until_complete(vm.devices['block'].attach(dev))
  1291. libvirt_xml = vm.create_config_file()
  1292. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1293. lxml.etree.XML(expected))
  1294. def test_610_libvirt_xml_network(self):
  1295. expected = '''<domain type="xen">
  1296. <name>test-inst-test</name>
  1297. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1298. <memory unit="MiB">500</memory>
  1299. <currentMemory unit="MiB">400</currentMemory>
  1300. <vcpu placement="static">2</vcpu>
  1301. <cpu mode='host-passthrough'>
  1302. <!-- disable nested HVM -->
  1303. <feature name='vmx' policy='disable'/>
  1304. <feature name='svm' policy='disable'/>
  1305. <!-- disable SMAP inside VM, because of Linux bug -->
  1306. <feature name='smap' policy='disable'/>
  1307. </cpu>
  1308. <os>
  1309. <type arch="x86_64" machine="xenfv">hvm</type>
  1310. <!--
  1311. For the libxl backend libvirt switches between OVMF (UEFI)
  1312. and SeaBIOS based on the loader type. This has nothing to
  1313. do with the hvmloader binary.
  1314. -->
  1315. <loader type="rom">hvmloader</loader>
  1316. <boot dev="cdrom" />
  1317. <boot dev="hd" />
  1318. </os>
  1319. <features>
  1320. <pae/>
  1321. <acpi/>
  1322. <apic/>
  1323. <viridian/>
  1324. </features>
  1325. <clock offset="variable" adjustment="0" basis="localtime" />
  1326. <on_poweroff>destroy</on_poweroff>
  1327. <on_reboot>destroy</on_reboot>
  1328. <on_crash>destroy</on_crash>
  1329. <devices>
  1330. <interface type="ethernet">
  1331. <mac address="00:16:3e:5e:6c:00" />
  1332. <ip address="10.137.0.1" />
  1333. {extra_ip}
  1334. <backenddomain name="test-inst-netvm" />
  1335. <script path="vif-route-qubes" />
  1336. </interface>
  1337. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1338. <emulator type="stubdom-linux" cmdline="-qubes-net:client_ip=10.137.0.1,dns_0=10.139.1.1,dns_1=10.139.1.2,gw=10.137.0.2,netmask=255.255.255.255" />
  1339. <input type="tablet" bus="usb"/>
  1340. <video>
  1341. <model type="vga"/>
  1342. </video>
  1343. <graphics type="qubes"/>
  1344. <console type="pty">
  1345. <target type="xen" port="0"/>
  1346. </console>
  1347. </devices>
  1348. </domain>
  1349. '''
  1350. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1351. netvm = self.get_vm(qid=2, name='netvm', provides_network=True)
  1352. vm = self.get_vm(uuid=my_uuid)
  1353. vm.netvm = netvm
  1354. vm.virt_mode = 'hvm'
  1355. vm.features['qrexec'] = True
  1356. with self.subTest('ipv4_only'):
  1357. libvirt_xml = vm.create_config_file()
  1358. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1359. lxml.etree.XML(expected.format(extra_ip='')))
  1360. with self.subTest('ipv6'):
  1361. netvm.features['ipv6'] = True
  1362. libvirt_xml = vm.create_config_file()
  1363. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1364. lxml.etree.XML(expected.format(
  1365. extra_ip='<ip address="{}::a89:1" family=\'ipv6\'/>'.format(
  1366. qubes.config.qubes_ipv6_prefix.replace(':0000', '')))))
  1367. def test_615_libvirt_xml_block_devices(self):
  1368. expected = '''<domain type="xen">
  1369. <name>test-inst-test</name>
  1370. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1371. <memory unit="MiB">400</memory>
  1372. <currentMemory unit="MiB">400</currentMemory>
  1373. <vcpu placement="static">2</vcpu>
  1374. <cpu mode='host-passthrough'>
  1375. <!-- disable nested HVM -->
  1376. <feature name='vmx' policy='disable'/>
  1377. <feature name='svm' policy='disable'/>
  1378. <!-- disable SMAP inside VM, because of Linux bug -->
  1379. <feature name='smap' policy='disable'/>
  1380. </cpu>
  1381. <os>
  1382. <type arch="x86_64" machine="xenfv">hvm</type>
  1383. <!--
  1384. For the libxl backend libvirt switches between OVMF (UEFI)
  1385. and SeaBIOS based on the loader type. This has nothing to
  1386. do with the hvmloader binary.
  1387. -->
  1388. <loader type="rom">hvmloader</loader>
  1389. <boot dev="cdrom" />
  1390. <boot dev="hd" />
  1391. </os>
  1392. <features>
  1393. <pae/>
  1394. <acpi/>
  1395. <apic/>
  1396. <viridian/>
  1397. </features>
  1398. <clock offset="variable" adjustment="0" basis="localtime" />
  1399. <on_poweroff>destroy</on_poweroff>
  1400. <on_reboot>destroy</on_reboot>
  1401. <on_crash>destroy</on_crash>
  1402. <devices>
  1403. <disk type="block" device="disk">
  1404. <driver name="phy" />
  1405. <source dev="/dev/loop0" />
  1406. <target dev="xvda" />
  1407. <backenddomain name="dom0" />
  1408. <script path="/tmp/script" />
  1409. </disk>
  1410. <disk type="block" device="disk">
  1411. <driver name="phy" />
  1412. <source dev="/dev/loop1" />
  1413. <target dev="xvde" />
  1414. <backenddomain name="dom0" />
  1415. </disk>
  1416. <disk type="block" device="disk">
  1417. <driver name="phy" />
  1418. <source dev="/dev/loop2" />
  1419. <target dev="xvdf" />
  1420. <backenddomain name="dom0" />
  1421. </disk>
  1422. <disk type="block" device="disk">
  1423. <driver name="phy" />
  1424. <source dev="/dev/sdb" />
  1425. <target dev="xvdl" />
  1426. </disk>
  1427. <disk type="block" device="cdrom">
  1428. <driver name="phy" />
  1429. <source dev="/dev/sda" />
  1430. <!-- prefer xvdd for CDROM -->
  1431. <target dev="xvdd" />
  1432. </disk>
  1433. <disk type="block" device="disk">
  1434. <driver name="phy" />
  1435. <source dev="/dev/loop0" />
  1436. <target dev="xvdi" />
  1437. <backenddomain name="backend0" />
  1438. </disk>
  1439. <disk type="block" device="disk">
  1440. <driver name="phy" />
  1441. <source dev="/dev/loop0" />
  1442. <target dev="xvdj" />
  1443. <backenddomain name="backend1" />
  1444. </disk>
  1445. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1446. <emulator type="stubdom-linux" />
  1447. <input type="tablet" bus="usb"/>
  1448. <video>
  1449. <model type="vga"/>
  1450. </video>
  1451. <graphics type="qubes"/>
  1452. <console type="pty">
  1453. <target type="xen" port="0"/>
  1454. </console>
  1455. </devices>
  1456. </domain>
  1457. '''
  1458. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1459. vm = self.get_vm(uuid=my_uuid)
  1460. vm.netvm = None
  1461. vm.virt_mode = 'hvm'
  1462. vm.volumes['root'] = unittest.mock.Mock(**{
  1463. 'block_device.return_value.name': 'root',
  1464. 'block_device.return_value.path': '/dev/loop0',
  1465. 'block_device.return_value.devtype': 'disk',
  1466. 'block_device.return_value.domain': 'dom0',
  1467. 'block_device.return_value.script': '/tmp/script',
  1468. })
  1469. vm.volumes['other'] = unittest.mock.Mock(**{
  1470. 'block_device.return_value.name': 'other',
  1471. 'block_device.return_value.path': '/dev/loop1',
  1472. 'block_device.return_value.devtype': 'disk',
  1473. 'block_device.return_value.domain': 'dom0',
  1474. 'block_device.return_value.script': None,
  1475. })
  1476. vm.volumes['other2'] = unittest.mock.Mock(**{
  1477. 'block_device.return_value.name': 'other',
  1478. 'block_device.return_value.path': '/dev/loop2',
  1479. 'block_device.return_value.devtype': 'disk',
  1480. 'block_device.return_value.domain': 'dom0',
  1481. 'block_device.return_value.script': None,
  1482. })
  1483. assignments = [
  1484. unittest.mock.Mock(**{
  1485. 'options': {'frontend-dev': 'xvdl'},
  1486. 'device.device_node': '/dev/sdb',
  1487. 'device.backend_domain.name': 'dom0',
  1488. }),
  1489. unittest.mock.Mock(**{
  1490. 'options': {'devtype': 'cdrom'},
  1491. 'device.device_node': '/dev/sda',
  1492. 'device.backend_domain.name': 'dom0',
  1493. }),
  1494. unittest.mock.Mock(**{
  1495. 'options': {'read-only': True},
  1496. 'device.device_node': '/dev/loop0',
  1497. 'device.backend_domain.name': 'backend0',
  1498. }),
  1499. unittest.mock.Mock(**{
  1500. 'options': {},
  1501. 'device.device_node': '/dev/loop0',
  1502. 'device.backend_domain.name': 'backend1',
  1503. }),
  1504. ]
  1505. vm.devices['block'].assignments = lambda persistent: assignments
  1506. libvirt_xml = vm.create_config_file()
  1507. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1508. lxml.etree.XML(expected))
  1509. @unittest.mock.patch('qubes.utils.get_timezone')
  1510. @unittest.mock.patch('qubes.utils.urandom')
  1511. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1512. def test_620_qdb_standalone(self, mock_qubesdb, mock_urandom,
  1513. mock_timezone):
  1514. mock_urandom.return_value = b'A' * 64
  1515. mock_timezone.return_value = 'UTC'
  1516. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM)
  1517. vm.netvm = None
  1518. vm.events_enabled = True
  1519. test_qubesdb = TestQubesDB()
  1520. mock_qubesdb.write.side_effect = test_qubesdb.write
  1521. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1522. vm.create_qdb_entries()
  1523. self.maxDiff = None
  1524. iptables_header = (
  1525. '# Generated by Qubes Core on {}\n'
  1526. '*filter\n'
  1527. ':INPUT DROP [0:0]\n'
  1528. ':FORWARD DROP [0:0]\n'
  1529. ':OUTPUT ACCEPT [0:0]\n'
  1530. '-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n'
  1531. '-A INPUT -m conntrack --ctstate '
  1532. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1533. '-A INPUT -p icmp -j ACCEPT\n'
  1534. '-A INPUT -i lo -j ACCEPT\n'
  1535. '-A INPUT -j REJECT --reject-with '
  1536. 'icmp-host-prohibited\n'
  1537. '-A FORWARD -m conntrack --ctstate '
  1538. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1539. '-A FORWARD -i vif+ -o vif+ -j DROP\n'
  1540. 'COMMIT\n'.format(datetime.datetime.now().ctime()))
  1541. self.assertEqual(test_qubesdb.data, {
  1542. '/name': 'test-inst-test',
  1543. '/type': 'StandaloneVM',
  1544. '/default-user': 'user',
  1545. '/qubes-vm-type': 'AppVM',
  1546. '/qubes-debug-mode': '0',
  1547. '/qubes-base-template': '',
  1548. '/qubes-timezone': 'UTC',
  1549. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1550. '/qubes-vm-persistence': 'full',
  1551. '/qubes-vm-updateable': 'True',
  1552. '/qubes-block-devices': '',
  1553. '/qubes-usb-devices': '',
  1554. '/qubes-iptables': 'reload',
  1555. '/qubes-iptables-error': '',
  1556. '/qubes-iptables-header': iptables_header,
  1557. '/qubes-service/qubes-update-check': '0',
  1558. '/qubes-service/meminfo-writer': '1',
  1559. '/connected-ips': '',
  1560. '/connected-ips6': '',
  1561. })
  1562. @unittest.mock.patch('datetime.datetime')
  1563. @unittest.mock.patch('qubes.utils.get_timezone')
  1564. @unittest.mock.patch('qubes.utils.urandom')
  1565. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1566. def test_621_qdb_vm_with_network(self, mock_qubesdb, mock_urandom,
  1567. mock_timezone, mock_datetime):
  1568. mock_urandom.return_value = b'A' * 64
  1569. mock_timezone.return_value = 'UTC'
  1570. template = self.get_vm(cls=qubes.vm.templatevm.TemplateVM, name='template')
  1571. template.netvm = None
  1572. netvm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1573. name='netvm', qid=2, provides_network=True)
  1574. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1575. name='appvm', qid=3)
  1576. vm.netvm = netvm
  1577. vm.kernel = None
  1578. # pretend the VM is running...
  1579. vm._qubesprop_xid = 3
  1580. netvm.kernel = None
  1581. test_qubesdb = TestQubesDB()
  1582. mock_qubesdb.write.side_effect = test_qubesdb.write
  1583. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1584. self.maxDiff = None
  1585. mock_datetime.now.returnvalue = \
  1586. datetime.datetime(2019, 2, 27, 15, 12, 15, 385822)
  1587. iptables_header = (
  1588. '# Generated by Qubes Core on {}\n'
  1589. '*filter\n'
  1590. ':INPUT DROP [0:0]\n'
  1591. ':FORWARD DROP [0:0]\n'
  1592. ':OUTPUT ACCEPT [0:0]\n'
  1593. '-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n'
  1594. '-A INPUT -m conntrack --ctstate '
  1595. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1596. '-A INPUT -p icmp -j ACCEPT\n'
  1597. '-A INPUT -i lo -j ACCEPT\n'
  1598. '-A INPUT -j REJECT --reject-with '
  1599. 'icmp-host-prohibited\n'
  1600. '-A FORWARD -m conntrack --ctstate '
  1601. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1602. '-A FORWARD -i vif+ -o vif+ -j DROP\n'
  1603. 'COMMIT\n'.format(datetime.datetime.now().ctime()))
  1604. expected = {
  1605. '/name': 'test-inst-appvm',
  1606. '/type': 'AppVM',
  1607. '/default-user': 'user',
  1608. '/qubes-vm-type': 'AppVM',
  1609. '/qubes-debug-mode': '0',
  1610. '/qubes-base-template': 'test-inst-template',
  1611. '/qubes-timezone': 'UTC',
  1612. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1613. '/qubes-vm-persistence': 'rw-only',
  1614. '/qubes-vm-updateable': 'False',
  1615. '/qubes-block-devices': '',
  1616. '/qubes-usb-devices': '',
  1617. '/qubes-iptables': 'reload',
  1618. '/qubes-iptables-error': '',
  1619. '/qubes-iptables-header': iptables_header,
  1620. '/qubes-service/qubes-update-check': '0',
  1621. '/qubes-service/meminfo-writer': '1',
  1622. '/qubes-mac': '00:16:3e:5e:6c:00',
  1623. '/qubes-ip': '10.137.0.3',
  1624. '/qubes-netmask': '255.255.255.255',
  1625. '/qubes-gateway': '10.137.0.2',
  1626. '/qubes-primary-dns': '10.139.1.1',
  1627. '/qubes-secondary-dns': '10.139.1.2',
  1628. '/connected-ips': '',
  1629. '/connected-ips6': '',
  1630. }
  1631. with self.subTest('ipv4'):
  1632. vm.create_qdb_entries()
  1633. self.assertEqual(test_qubesdb.data, expected)
  1634. test_qubesdb.data.clear()
  1635. with self.subTest('ipv6'):
  1636. netvm.features['ipv6'] = True
  1637. expected['/qubes-ip6'] = \
  1638. qubes.config.qubes_ipv6_prefix.replace(':0000', '') + \
  1639. '::a89:3'
  1640. expected['/qubes-gateway6'] = expected['/qubes-ip6'][:-1] + '2'
  1641. vm.create_qdb_entries()
  1642. self.assertEqual(test_qubesdb.data, expected)
  1643. test_qubesdb.data.clear()
  1644. with self.subTest('ipv6_just_appvm'):
  1645. del netvm.features['ipv6']
  1646. vm.features['ipv6'] = True
  1647. expected['/qubes-ip6'] = \
  1648. qubes.config.qubes_ipv6_prefix.replace(':0000', '') + \
  1649. '::a89:3'
  1650. del expected['/qubes-gateway6']
  1651. vm.create_qdb_entries()
  1652. self.assertEqual(test_qubesdb.data, expected)
  1653. test_qubesdb.data.clear()
  1654. with self.subTest('proxy_ipv4'):
  1655. del vm.features['ipv6']
  1656. expected['/name'] = 'test-inst-netvm'
  1657. expected['/qubes-vm-type'] = 'NetVM'
  1658. del expected['/qubes-ip']
  1659. del expected['/qubes-gateway']
  1660. del expected['/qubes-netmask']
  1661. del expected['/qubes-ip6']
  1662. del expected['/qubes-primary-dns']
  1663. del expected['/qubes-secondary-dns']
  1664. del expected['/qubes-mac']
  1665. expected['/qubes-netvm-primary-dns'] = '10.139.1.1'
  1666. expected['/qubes-netvm-secondary-dns'] = '10.139.1.2'
  1667. expected['/qubes-netvm-network'] = '10.137.0.2'
  1668. expected['/qubes-netvm-gateway'] = '10.137.0.2'
  1669. expected['/qubes-netvm-netmask'] = '255.255.255.255'
  1670. expected['/qubes-iptables-domainrules/3'] = \
  1671. '*filter\n' \
  1672. '-A FORWARD -s 10.137.0.3 -j ACCEPT\n' \
  1673. '-A FORWARD -s 10.137.0.3 -j DROP\n' \
  1674. 'COMMIT\n'
  1675. expected['/mapped-ip/10.137.0.3/visible-ip'] = '10.137.0.3'
  1676. expected['/mapped-ip/10.137.0.3/visible-gateway'] = '10.137.0.2'
  1677. expected['/qubes-firewall/10.137.0.3'] = ''
  1678. expected['/qubes-firewall/10.137.0.3/0000'] = 'action=accept'
  1679. expected['/qubes-firewall/10.137.0.3/policy'] = 'drop'
  1680. expected['/connected-ips'] = '10.137.0.3'
  1681. with unittest.mock.patch('qubes.vm.qubesvm.QubesVM.is_running',
  1682. lambda _: True):
  1683. netvm.create_qdb_entries()
  1684. self.assertEqual(test_qubesdb.data, expected)
  1685. test_qubesdb.data.clear()
  1686. with self.subTest('proxy_ipv6'):
  1687. netvm.features['ipv6'] = True
  1688. ip6 = qubes.config.qubes_ipv6_prefix.replace(
  1689. ':0000', '') + '::a89:3'
  1690. expected['/qubes-netvm-gateway6'] = ip6[:-1] + '2'
  1691. expected['/qubes-firewall/' + ip6] = ''
  1692. expected['/qubes-firewall/' + ip6 + '/0000'] = 'action=accept'
  1693. expected['/qubes-firewall/' + ip6 + '/policy'] = 'drop'
  1694. expected['/connected-ips6'] = ip6
  1695. with unittest.mock.patch('qubes.vm.qubesvm.QubesVM.is_running',
  1696. lambda _: True):
  1697. netvm.create_qdb_entries()
  1698. self.assertEqual(test_qubesdb.data, expected)
  1699. @unittest.mock.patch('qubes.utils.get_timezone')
  1700. @unittest.mock.patch('qubes.utils.urandom')
  1701. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1702. def test_622_qdb_guivm_keyboard_layout(self, mock_qubesdb, mock_urandom,
  1703. mock_timezone):
  1704. mock_urandom.return_value = b'A' * 64
  1705. mock_timezone.return_value = 'UTC'
  1706. template = self.get_vm(
  1707. cls=qubes.vm.templatevm.TemplateVM, name='template')
  1708. template.netvm = None
  1709. guivm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1710. name='sys-gui', qid=2, provides_network=False)
  1711. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1712. name='appvm', qid=3)
  1713. vm.netvm = None
  1714. vm.guivm = guivm
  1715. guivm.features['keyboard-layout'] = 'fr'
  1716. xkb_keymap = \
  1717. 'xkb_keymap {\x0a\x09xkb_keycodes { include ' \
  1718. '"evdev"\x09};\x0a\x09xkb_types { include ' \
  1719. '"complete"\x09};\x0a\x09xkb_compat { include ' \
  1720. '"complete"\x09};\x0a\x09xkb_symbols { include ' \
  1721. '"pc+fr+inet(evdev)"\x09};\x0a\x09xkb_geometry ' \
  1722. '{ include "pc(pc105)"\x09};\x0a};'
  1723. guivm.is_running = lambda: True
  1724. vm.events_enabled = True
  1725. test_qubesdb = TestQubesDB()
  1726. mock_qubesdb.write.side_effect = test_qubesdb.write
  1727. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1728. vm.create_qdb_entries()
  1729. self.maxDiff = None
  1730. self.assertEqual(test_qubesdb.data, {
  1731. '/name': 'test-inst-appvm',
  1732. '/type': 'AppVM',
  1733. '/default-user': 'user',
  1734. '/qubes-keyboard': xkb_keymap,
  1735. '/keyboard-layout': 'fr',
  1736. '/qubes-vm-type': 'AppVM',
  1737. '/qubes-gui-domain-xid': '{}'.format(guivm.xid),
  1738. '/qubes-debug-mode': '0',
  1739. '/qubes-base-template': 'test-inst-template',
  1740. '/qubes-timezone': 'UTC',
  1741. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1742. '/qubes-vm-persistence': 'rw-only',
  1743. '/qubes-vm-updateable': 'False',
  1744. '/qubes-block-devices': '',
  1745. '/qubes-usb-devices': '',
  1746. '/qubes-iptables': 'reload',
  1747. '/qubes-iptables-error': '',
  1748. '/qubes-iptables-header': unittest.mock.ANY,
  1749. '/qubes-service/qubes-update-check': '0',
  1750. '/qubes-service/meminfo-writer': '1',
  1751. '/connected-ips': '',
  1752. '/connected-ips6': '',
  1753. })
  1754. @unittest.mock.patch('qubes.utils.get_timezone')
  1755. @unittest.mock.patch('qubes.utils.urandom')
  1756. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1757. def test_623_qdb_audiovm(self, mock_qubesdb, mock_urandom,
  1758. mock_timezone):
  1759. mock_urandom.return_value = b'A' * 64
  1760. mock_timezone.return_value = 'UTC'
  1761. template = self.get_vm(
  1762. cls=qubes.vm.templatevm.TemplateVM, name='template')
  1763. template.netvm = None
  1764. audiovm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1765. name='sys-audio', qid=2, provides_network=False)
  1766. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1767. name='appvm', qid=3)
  1768. vm.netvm = None
  1769. vm.audiovm = audiovm
  1770. audiovm.is_running = lambda: True
  1771. vm.events_enabled = True
  1772. test_qubesdb = TestQubesDB()
  1773. mock_qubesdb.write.side_effect = test_qubesdb.write
  1774. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1775. vm.create_qdb_entries()
  1776. self.maxDiff = None
  1777. self.assertEqual(test_qubesdb.data, {
  1778. '/name': 'test-inst-appvm',
  1779. '/type': 'AppVM',
  1780. '/default-user': 'user',
  1781. '/qubes-vm-type': 'AppVM',
  1782. '/qubes-audio-domain-xid': '{}'.format(audiovm.xid),
  1783. '/qubes-debug-mode': '0',
  1784. '/qubes-base-template': 'test-inst-template',
  1785. '/qubes-timezone': 'UTC',
  1786. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1787. '/qubes-vm-persistence': 'rw-only',
  1788. '/qubes-vm-updateable': 'False',
  1789. '/qubes-block-devices': '',
  1790. '/qubes-usb-devices': '',
  1791. '/qubes-iptables': 'reload',
  1792. '/qubes-iptables-error': '',
  1793. '/qubes-iptables-header': unittest.mock.ANY,
  1794. '/qubes-service/qubes-update-check': '0',
  1795. '/qubes-service/meminfo-writer': '1',
  1796. '/connected-ips': '',
  1797. '/connected-ips6': '',
  1798. })
  1799. @asyncio.coroutine
  1800. def coroutine_mock(self, mock, *args, **kwargs):
  1801. return mock(*args, **kwargs)
  1802. @unittest.mock.patch('asyncio.create_subprocess_exec')
  1803. def test_700_run_service(self, mock_subprocess):
  1804. func_mock = unittest.mock.Mock()
  1805. mock_subprocess.side_effect = functools.partial(
  1806. self.coroutine_mock, func_mock)
  1807. start_mock = unittest.mock.Mock()
  1808. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM,
  1809. name='vm')
  1810. vm.is_running = lambda: True
  1811. vm.is_qrexec_running = lambda: True
  1812. vm.start = functools.partial(self.coroutine_mock, start_mock)
  1813. with self.subTest('running'):
  1814. self.loop.run_until_complete(vm.run_service('test.service'))
  1815. func_mock.assert_called_once_with(
  1816. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1817. 'user:QUBESRPC test.service dom0')
  1818. self.assertFalse(start_mock.called)
  1819. func_mock.reset_mock()
  1820. start_mock.reset_mock()
  1821. with self.subTest('not_running'):
  1822. vm.is_running = lambda: False
  1823. with self.assertRaises(qubes.exc.QubesVMNotRunningError):
  1824. self.loop.run_until_complete(vm.run_service('test.service'))
  1825. self.assertFalse(func_mock.called)
  1826. func_mock.reset_mock()
  1827. start_mock.reset_mock()
  1828. with self.subTest('autostart'):
  1829. vm.is_running = lambda: False
  1830. self.loop.run_until_complete(vm.run_service(
  1831. 'test.service', autostart=True))
  1832. func_mock.assert_called_once_with(
  1833. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1834. 'user:QUBESRPC test.service dom0')
  1835. self.assertTrue(start_mock.called)
  1836. func_mock.reset_mock()
  1837. start_mock.reset_mock()
  1838. with self.subTest('no_qrexec'):
  1839. vm.is_running = lambda: True
  1840. vm.is_qrexec_running = lambda: False
  1841. with self.assertRaises(qubes.exc.QubesVMError):
  1842. self.loop.run_until_complete(vm.run_service('test.service'))
  1843. self.assertFalse(start_mock.called)
  1844. self.assertFalse(func_mock.called)
  1845. func_mock.reset_mock()
  1846. start_mock.reset_mock()
  1847. with self.subTest('other_user'):
  1848. vm.is_running = lambda: True
  1849. vm.is_qrexec_running = lambda: True
  1850. self.loop.run_until_complete(vm.run_service('test.service',
  1851. user='other'))
  1852. func_mock.assert_called_once_with(
  1853. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1854. 'other:QUBESRPC test.service dom0')
  1855. self.assertFalse(start_mock.called)
  1856. func_mock.reset_mock()
  1857. start_mock.reset_mock()
  1858. with self.subTest('other_source'):
  1859. vm.is_running = lambda: True
  1860. vm.is_qrexec_running = lambda: True
  1861. self.loop.run_until_complete(vm.run_service('test.service',
  1862. source='test-inst-vm'))
  1863. func_mock.assert_called_once_with(
  1864. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1865. 'user:QUBESRPC test.service test-inst-vm')
  1866. self.assertFalse(start_mock.called)
  1867. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.run_service')
  1868. def test_710_run_service_for_stdio(self, mock_run_service):
  1869. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM,
  1870. name='vm')
  1871. func_mock = unittest.mock.Mock()
  1872. mock_run_service.side_effect = functools.partial(
  1873. self.coroutine_mock, func_mock)
  1874. communicate_mock = unittest.mock.Mock()
  1875. func_mock.return_value.communicate.side_effect = functools.partial(
  1876. self.coroutine_mock, communicate_mock)
  1877. communicate_mock.return_value = (b'stdout', b'stderr')
  1878. func_mock.return_value.returncode = 0
  1879. with self.subTest('default'):
  1880. value = self.loop.run_until_complete(
  1881. vm.run_service_for_stdio('test.service'))
  1882. func_mock.assert_called_once_with(
  1883. 'test.service',
  1884. stdout=subprocess.PIPE,
  1885. stderr=subprocess.PIPE,
  1886. stdin=subprocess.PIPE)
  1887. communicate_mock.assert_called_once_with(input=None)
  1888. self.assertEqual(value, (b'stdout', b'stderr'))
  1889. func_mock.reset_mock()
  1890. communicate_mock.reset_mock()
  1891. with self.subTest('with_input'):
  1892. value = self.loop.run_until_complete(
  1893. vm.run_service_for_stdio('test.service', input=b'abc'))
  1894. func_mock.assert_called_once_with(
  1895. 'test.service',
  1896. stdout=subprocess.PIPE,
  1897. stderr=subprocess.PIPE,
  1898. stdin=subprocess.PIPE)
  1899. communicate_mock.assert_called_once_with(input=b'abc')
  1900. self.assertEqual(value, (b'stdout', b'stderr'))
  1901. func_mock.reset_mock()
  1902. communicate_mock.reset_mock()
  1903. with self.subTest('error'):
  1904. func_mock.return_value.returncode = 1
  1905. with self.assertRaises(subprocess.CalledProcessError) as exc:
  1906. self.loop.run_until_complete(
  1907. vm.run_service_for_stdio('test.service'))
  1908. func_mock.assert_called_once_with(
  1909. 'test.service',
  1910. stdout=subprocess.PIPE,
  1911. stderr=subprocess.PIPE,
  1912. stdin=subprocess.PIPE)
  1913. communicate_mock.assert_called_once_with(input=None)
  1914. self.assertEqual(exc.exception.returncode, 1)
  1915. self.assertEqual(exc.exception.output, b'stdout')
  1916. self.assertEqual(exc.exception.stderr, b'stderr')