qubesvm.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. from __future__ import absolute_import
  23. import asyncio
  24. import base64
  25. import datetime
  26. import errno
  27. import grp
  28. import os
  29. import os.path
  30. import shutil
  31. import string
  32. import subprocess
  33. import uuid
  34. import warnings
  35. import libvirt # pylint: disable=import-error
  36. import lxml
  37. import qubes
  38. import qubes.config
  39. import qubes.exc
  40. import qubes.storage
  41. import qubes.storage.file
  42. import qubes.utils
  43. import qubes.vm
  44. import qubes.vm.mix.net
  45. qmemman_present = False
  46. try:
  47. import qubes.qmemman.client # pylint: disable=wrong-import-position
  48. qmemman_present = True
  49. except ImportError:
  50. pass
  51. MEM_OVERHEAD_BASE = (3 + 1) * 1024 * 1024
  52. MEM_OVERHEAD_PER_VCPU = 3 * 1024 * 1024 / 2
  53. def _setter_kernel(self, prop, value):
  54. ''' Helper for setting the domain kernel and running sanity checks on it.
  55. ''' # pylint: disable=unused-argument
  56. if not value:
  57. return ''
  58. value = str(value)
  59. if '/' in value:
  60. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  61. 'Kernel name cannot contain \'/\'')
  62. return value
  63. def _setter_positive_int(self, prop, value):
  64. ''' Helper for setting a positive int. Checks that the int is >= 0 '''
  65. # pylint: disable=unused-argument
  66. value = int(value)
  67. if value <= 0:
  68. raise ValueError('Value must be positive')
  69. return value
  70. def _setter_default_user(self, prop, value):
  71. ''' Helper for setting default user '''
  72. value = str(value)
  73. # specifically forbid: ':', ' ', ''', '"'
  74. allowed_chars = string.ascii_letters + string.digits + '_-+,.'
  75. if not all(c in allowed_chars for c in value):
  76. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  77. 'Username can contain only those characters: ' + allowed_chars)
  78. return value
  79. def _setter_virt_mode(self, prop, value):
  80. value = str(value)
  81. value = value.lower()
  82. if value not in ('hvm', 'pv', 'pvh'):
  83. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  84. 'Invalid virtualization mode, supported values: hvm, pv, pvh')
  85. return value
  86. class QubesVM(qubes.vm.mix.net.NetVMMixin, qubes.vm.BaseVM):
  87. '''Base functionality of Qubes VM shared between all VMs.
  88. The following events are raised on this class or its subclasses:
  89. .. event:: domain-init (subject, event)
  90. Fired at the end of class' constructor.
  91. :param subject: Event emitter (the qube object)
  92. :param event: Event name (``'domain-init'``)
  93. .. event:: domain-load (subject, event)
  94. Fired after the qube was loaded from :file:`qubes.xml`
  95. :param subject: Event emitter (the qube object)
  96. :param event: Event name (``'domain-loaded'``)
  97. .. event:: domain-pre-start \
  98. (subject, event, start_guid, mem_required)
  99. Fired at the beginning of :py:meth:`start` method.
  100. Handler for this event can be asynchronous (a coroutine).
  101. :param subject: Event emitter (the qube object)
  102. :param event: Event name (``'domain-pre-start'``)
  103. *other arguments are as in :py:meth:`start`*
  104. .. event:: domain-spawn (subject, event, start_guid)
  105. Fired after creating libvirt domain.
  106. :param subject: Event emitter (the qube object)
  107. :param event: Event name (``'domain-spawn'``)
  108. Handler for this event can be asynchronous (a coroutine).
  109. *other arguments are as in :py:meth:`start`*
  110. .. event:: domain-start (subject, event, start_guid)
  111. Fired at the end of :py:meth:`start` method.
  112. Handler for this event can be asynchronous (a coroutine).
  113. :param subject: Event emitter (the qube object)
  114. :param event: Event name (``'domain-start'``)
  115. *other arguments are as in :py:meth:`start`*
  116. .. event:: domain-shutdown (subject, event)
  117. Fired when domain has been shut down.
  118. :param subject: Event emitter (the qube object)
  119. :param event: Event name (``'domain-shutdown'``)
  120. .. event:: domain-pre-shutdown (subject, event, force)
  121. Fired at the beginning of :py:meth:`shutdown` method.
  122. Handler for this event can be asynchronous (a coroutine).
  123. :param subject: Event emitter (the qube object)
  124. :param event: Event name (``'domain-pre-shutdown'``)
  125. :param force: If the shutdown is to be forceful
  126. .. event:: domain-cmd-pre-run (subject, event, start_guid)
  127. Fired at the beginning of :py:meth:`run_service` method.
  128. Handler for this event can be asynchronous (a coroutine).
  129. :param subject: Event emitter (the qube object)
  130. :param event: Event name (``'domain-cmd-pre-run'``)
  131. :param start_guid: If the gui daemon can be started
  132. .. event:: domain-create-on-disk (subject, event)
  133. Fired at the end of :py:meth:`create_on_disk` method.
  134. Handler for this event can be asynchronous (a coroutine).
  135. :param subject: Event emitter (the qube object)
  136. :param event: Event name (``'domain-create-on-disk'``)
  137. .. event:: domain-remove-from-disk (subject, event)
  138. Fired at the beginning of :py:meth:`remove_from_disk` method, before
  139. the qube directory is removed.
  140. Handler for this event can be asynchronous (a coroutine).
  141. :param subject: Event emitter (the qube object)
  142. :param event: Event name (``'domain-remove-from-disk'``)
  143. .. event:: domain-clone-files (subject, event, src)
  144. Fired at the end of :py:meth:`clone_disk_files` method.
  145. Handler for this event can be asynchronous (a coroutine).
  146. :param subject: Event emitter (the qube object)
  147. :param event: Event name (``'domain-clone-files'``)
  148. :param src: source qube
  149. .. event:: domain-verify-files (subject, event)
  150. Fired at the end of :py:meth:`clone_disk_files` method.
  151. :param subject: Event emitter (the qube object)
  152. :param event: Event name (``'domain-verify-files'``)
  153. If you think some files are missing or damaged, raise an exception.
  154. .. event:: domain-is-fully-usable (subject, event)
  155. Fired at the end of :py:meth:`clone_disk_files` method.
  156. :param subject: Event emitter (the qube object)
  157. :param event: Event name (``'domain-is-fully-usable'``)
  158. You may ``yield False`` from the handler if you think the qube is
  159. not fully usable. This will cause the domain to be in "transient"
  160. state in the domain lifecycle.
  161. .. event:: domain-qdb-create (subject, event)
  162. Fired at the end of :py:meth:`create_qdb_entries` method.
  163. :param subject: Event emitter (the qube object)
  164. :param event: Event name (``'domain-qdb-create'``)
  165. This event is a good place to add your custom entries to the qdb.
  166. .. event:: domain-qdb-change:watched-path (subject, event, path)
  167. Fired when watched QubesDB entry is changed. See
  168. :py:meth:`watch_qdb_path`. *watched-path* part of event name is
  169. what path was registered for watching, *path* in event argument
  170. is what actually have changed (which may be different if watching a
  171. directory, i.e. a path with `/` at the end).
  172. :param subject: Event emitter (the qube object)
  173. :param event: Event name (``'domain-qdb-change'``)
  174. :param path: changed QubesDB path
  175. .. event:: backup-get-files (subject, event)
  176. Collects additional file to be included in a backup.
  177. :param subject: Event emitter (the qube object)
  178. :param event: Event name (``'backup-get-files'``)
  179. Handlers should yield paths of the files.
  180. .. event:: domain-restore (subject, event)
  181. Domain was just restored from backup, although the storage was not
  182. yet verified and the app object was not yet saved.
  183. :param subject: Event emitter (the qube object)
  184. :param event: Event name (``'domain-restore'``)
  185. .. event:: domain-feature-set (subject, event, feature, value
  186. [, oldvalue])
  187. A feature was changed.
  188. *oldvalue* is present only when there was any.
  189. :param subject: Event emitter (the qube object)
  190. :param event: Event name (``'domain-feature-set'``)
  191. :param feature: feature name
  192. :param value: new value
  193. :param oldvalue: old value, if any
  194. .. event:: domain-feature-delete (subject, event, feature)
  195. A feature was removed.
  196. :param subject: Event emitter (the qube object)
  197. :param event: Event name (``'domain-feature-delete'``)
  198. :param feature: feature name
  199. .. event:: domain-tag-add (subject, event, tag)
  200. A tag was added.
  201. :param subject: Event emitter (the qube object)
  202. :param event: Event name (``'domain-tag-add'``)
  203. :param tag: tag name
  204. .. event:: domain-tag-delete (subject, event, tag)
  205. A feature was removed.
  206. :param subject: Event emitter (the qube object)
  207. :param event: Event name (``'domain-tag-delete'``)
  208. :param tag: tag name
  209. .. event:: feature-request (subject, event, *, untrusted_features)
  210. The domain is performing a feature request.
  211. :param subject: Event emitter (the qube object)
  212. :param event: Event name (``'feature-request'``)
  213. :param untrusted_features: :py:class:`dict` containing the feature \
  214. request
  215. The content of the `untrusted_features` variable is, as the name
  216. implies, **UNTRUSTED**. The remind this to programmer, the variable
  217. name has to be exactly as provided.
  218. It is up to the extensions to decide, what to do with request,
  219. ranging from plainly ignoring the request to verbatim copy into
  220. :py:attr:`features` with only minimal sanitisation.
  221. .. event:: monitor-layout-change (subject, event, monitor_layout)
  222. Desktop layout was changed, probably because a display was plugged
  223. in or out.
  224. :param subject: Event emitter (the qube object)
  225. :param event: Event name (``'monitor-layout-change'``)
  226. :param monitor_layout: The new layout
  227. .. event:: firewall-changed (subject, event)
  228. Firewall was changed.
  229. :param subject: Event emitter (the qube object)
  230. :param event: Event name (``'firewall-changed'``)
  231. .. event:: net-domain-connect (subject, event, vm)
  232. Fired after connecting a domiain to this vm.
  233. :param subject: Event emitter (the qube object)
  234. :param event: Event name (``'net-domain-connect'``)
  235. :param vm: The domain that was just connected.
  236. On the `vm` object there was probably ``property-set:netvm`` fired
  237. earlier.
  238. '''
  239. #
  240. # per-class properties
  241. #
  242. #: directory in which domains of this class will reside
  243. dir_path_prefix = qubes.config.system_path['qubes_appvms_dir']
  244. #
  245. # properties loaded from XML
  246. #
  247. virt_mode = qubes.property('virt_mode',
  248. type=str, setter=_setter_virt_mode,
  249. default='hvm',
  250. doc='''Virtualisation mode: full virtualisation ("hvm"),
  251. or paravirtualisation ("pv")''')
  252. installed_by_rpm = qubes.property('installed_by_rpm',
  253. type=bool, setter=qubes.property.bool,
  254. default=False,
  255. doc='''If this domain's image was installed from package tracked by
  256. package manager.''')
  257. memory = qubes.property('memory', type=int,
  258. setter=_setter_positive_int,
  259. default=(lambda self:
  260. qubes.config.defaults[
  261. 'hvm_memory' if self.virt_mode == 'hvm' else 'memory']),
  262. doc='Memory currently available for this VM.')
  263. maxmem = qubes.property('maxmem', type=int,
  264. setter=_setter_positive_int,
  265. default=(lambda self:
  266. int(min(self.app.host.memory_total / 1024 / 2, 4000))),
  267. doc='''Maximum amount of memory available for this VM (for the purpose
  268. of the memory balancer).''')
  269. stubdom_mem = qubes.property('stubdom_mem', type=int,
  270. setter=_setter_positive_int,
  271. default=None,
  272. doc='Memory ammount allocated for the stubdom')
  273. vcpus = qubes.property('vcpus',
  274. type=int,
  275. setter=_setter_positive_int,
  276. default=2,
  277. doc='Number of virtual CPUs for a qube')
  278. # CORE2: swallowed uses_default_kernel
  279. kernel = qubes.property('kernel', type=str,
  280. setter=_setter_kernel,
  281. default=(lambda self: self.app.default_kernel),
  282. doc='Kernel used by this domain.')
  283. # CORE2: swallowed uses_default_kernelopts
  284. # pylint: disable=no-member
  285. kernelopts = qubes.property('kernelopts', type=str, load_stage=4,
  286. default=(lambda self: qubes.config.defaults['kernelopts_pcidevs']
  287. # pylint: disable=no-member
  288. if list(self.devices['pci'].persistent())
  289. else self.template.kernelopts if hasattr(self, 'template')
  290. else qubes.config.defaults['kernelopts']),
  291. doc='Kernel command line passed to domain.')
  292. debug = qubes.property('debug', type=bool, default=False,
  293. setter=qubes.property.bool,
  294. doc='Turns on debugging features.')
  295. # XXX what this exactly does?
  296. # XXX shouldn't this go to standalone VM and TemplateVM, and leave here
  297. # only plain property?
  298. default_user = qubes.property('default_user', type=str,
  299. # pylint: disable=no-member
  300. default=(lambda self: self.template.default_user
  301. if hasattr(self, 'template') else 'user'),
  302. setter=_setter_default_user,
  303. doc='FIXME')
  304. # pylint: enable=no-member
  305. # @property
  306. # def default_user(self):
  307. # if self.template is not None:
  308. # return self.template.default_user
  309. # else:
  310. # return self._default_user
  311. qrexec_timeout = qubes.property('qrexec_timeout', type=int, default=60,
  312. setter=_setter_positive_int,
  313. doc='''Time in seconds after which qrexec connection attempt is deemed
  314. failed. Operating system inside VM should be able to boot in this
  315. time.''')
  316. autostart = qubes.property('autostart', default=False,
  317. type=bool, setter=qubes.property.bool,
  318. doc='''Setting this to `True` means that VM should be autostarted on
  319. dom0 boot.''')
  320. include_in_backups = qubes.property('include_in_backups',
  321. default=True,
  322. type=bool, setter=qubes.property.bool,
  323. doc='If this domain is to be included in default backup.')
  324. # format got changed from %s to str(datetime.datetime)
  325. backup_timestamp = qubes.property('backup_timestamp', default=None,
  326. setter=(lambda self, prop, value:
  327. value if isinstance(value, datetime.datetime) else
  328. datetime.datetime.fromtimestamp(int(value))),
  329. saver=(lambda self, prop, value: value.strftime('%s')),
  330. doc='FIXME')
  331. default_dispvm = qubes.VMProperty('default_dispvm',
  332. load_stage=4,
  333. allow_none=True,
  334. default=(lambda self: self.app.default_dispvm),
  335. doc='Default VM to be used as Disposable VM for service calls.')
  336. updateable = qubes.property('updateable',
  337. default=(lambda self: not hasattr(self, 'template')),
  338. type=bool,
  339. setter=qubes.property.forbidden,
  340. doc='True if this machine may be updated on its own.')
  341. #
  342. # static, class-wide properties
  343. #
  344. #
  345. # properties not loaded from XML, calculated at run-time
  346. #
  347. def __str__(self):
  348. return self.name
  349. # VMM-related
  350. @qubes.stateless_property
  351. def xid(self):
  352. '''Xen ID.
  353. Or not Xen, but ID.
  354. '''
  355. if self.libvirt_domain is None:
  356. return -1
  357. try:
  358. return self.libvirt_domain.ID()
  359. except libvirt.libvirtError as e:
  360. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  361. return -1
  362. else:
  363. self.log.exception('libvirt error code: {!r}'.format(
  364. e.get_error_code()))
  365. raise
  366. @qubes.stateless_property
  367. def stubdom_xid(self):
  368. if not self.is_running():
  369. return -1
  370. if self.app.vmm.xs is None:
  371. return -1
  372. stubdom_xid_str = self.app.vmm.xs.read('',
  373. '/local/domain/{}/image/device-model-domid'.format(self.xid))
  374. if stubdom_xid_str is None or not stubdom_xid_str.isdigit():
  375. return -1
  376. return int(stubdom_xid_str)
  377. @property
  378. def attached_volumes(self):
  379. result = []
  380. xml_desc = self.libvirt_domain.XMLDesc()
  381. xml = lxml.etree.fromstring(xml_desc)
  382. for disk in xml.xpath("//domain/devices/disk"):
  383. if disk.find('backenddomain') is not None:
  384. pool_name = 'p_%s' % disk.find('backenddomain').get('name')
  385. pool = self.app.pools[pool_name]
  386. vid = disk.find('source').get('dev').split('/dev/')[1]
  387. for volume in pool.volumes:
  388. if volume.vid == vid:
  389. result += [volume]
  390. break
  391. return result + list(self.volumes.values())
  392. @property
  393. def libvirt_domain(self):
  394. '''Libvirt domain object from libvirt.
  395. May be :py:obj:`None`, if libvirt knows nothing about this domain.
  396. '''
  397. if self._libvirt_domain is not None:
  398. return self._libvirt_domain
  399. # XXX _update_libvirt_domain?
  400. try:
  401. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  402. self.uuid.bytes)
  403. except libvirt.libvirtError as e:
  404. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  405. self._update_libvirt_domain()
  406. else:
  407. raise
  408. return self._libvirt_domain
  409. @property
  410. def block_devices(self):
  411. ''' Return all :py:class:`qubes.storage.BlockDevice` for current domain
  412. for serialization in the libvirt XML template as <disk>.
  413. '''
  414. for v in self.volumes.values():
  415. block_dev = v.block_device()
  416. if block_dev is not None:
  417. yield block_dev
  418. @property
  419. def untrusted_qdb(self):
  420. '''QubesDB handle for this domain.'''
  421. if self._qdb_connection is None:
  422. if self.is_running():
  423. import qubesdb # pylint: disable=import-error
  424. self._qdb_connection = qubesdb.QubesDB(self.name)
  425. return self._qdb_connection
  426. @property
  427. def dir_path(self):
  428. '''Root directory for files related to this domain'''
  429. return os.path.join(
  430. qubes.config.qubes_base_dir,
  431. self.dir_path_prefix,
  432. self.name)
  433. @property
  434. def icon_path(self):
  435. return os.path.join(self.dir_path, 'icon.png')
  436. @property
  437. def conf_file(self):
  438. return os.path.join(self.dir_path, 'libvirt.xml')
  439. # network-related
  440. #
  441. # constructor
  442. #
  443. def __init__(self, app, xml, volume_config=None, **kwargs):
  444. # migrate renamed properties
  445. if xml is not None:
  446. node_hvm = xml.find('./properties/property[@name=\'hvm\']')
  447. if node_hvm is not None:
  448. if qubes.property.bool(None, None, node_hvm.text):
  449. kwargs['virt_mode'] = 'hvm'
  450. else:
  451. kwargs['virt_mode'] = 'pv'
  452. node_hvm.getparent().remove(node_hvm)
  453. super(QubesVM, self).__init__(app, xml, **kwargs)
  454. if volume_config is None:
  455. volume_config = {}
  456. if hasattr(self, 'volume_config'):
  457. if xml is not None:
  458. for node in xml.xpath('volume-config/volume'):
  459. name = node.get('name')
  460. assert name
  461. for key, value in node.items():
  462. # pylint: disable=no-member
  463. if value == 'True':
  464. value = True
  465. try:
  466. self.volume_config[name][key] = value
  467. except KeyError:
  468. self.volume_config[name] = {key: value}
  469. for name, conf in volume_config.items():
  470. for key, value in conf.items():
  471. # pylint: disable=no-member
  472. try:
  473. self.volume_config[name][key] = value
  474. except KeyError:
  475. self.volume_config[name] = {key: value}
  476. elif volume_config:
  477. raise TypeError(
  478. 'volume_config specified, but {} did not expect that.'.format(
  479. self.__class__.__name__))
  480. # Init private attrs
  481. self._libvirt_domain = None
  482. self._qdb_connection = None
  483. if xml is None:
  484. # we are creating new VM and attributes came through kwargs
  485. assert hasattr(self, 'qid')
  486. assert hasattr(self, 'name')
  487. # Linux specific cap: max memory can't scale beyond 10.79*init_mem
  488. # see https://groups.google.com/forum/#!topic/qubes-devel/VRqkFj1IOtA
  489. if self.maxmem > self.memory * 10:
  490. self.maxmem = self.memory * 10
  491. if xml is None:
  492. # new qube, disable updates check if requested for new qubes
  493. # SEE: 1637 when features are done, migrate to plugin
  494. if not self.app.check_updates_vm:
  495. self.features['check-updates'] = False
  496. # will be initialized after loading all the properties
  497. #: operations which shouldn't happen simultaneously with qube startup
  498. # (including another startup of the same qube)
  499. self.startup_lock = asyncio.Lock()
  500. # fire hooks
  501. if xml is None:
  502. self.events_enabled = True
  503. self.fire_event('domain-init')
  504. def close(self):
  505. if self._qdb_connection is not None:
  506. self._qdb_connection.close()
  507. self._qdb_connection = None
  508. if self._libvirt_domain is not None:
  509. self._libvirt_domain = None
  510. super().close()
  511. def __hash__(self):
  512. return self.qid
  513. def __lt__(self, other):
  514. return self.name < other.name
  515. def __xml__(self):
  516. element = super(QubesVM, self).__xml__()
  517. if hasattr(self, 'volumes'):
  518. volume_config_node = lxml.etree.Element('volume-config')
  519. for volume in self.volumes.values():
  520. volume_config_node.append(volume.__xml__())
  521. element.append(volume_config_node)
  522. return element
  523. #
  524. # event handlers
  525. #
  526. @qubes.events.handler('domain-init', 'domain-load')
  527. def on_domain_init_loaded(self, event):
  528. # pylint: disable=unused-argument
  529. if not hasattr(self, 'uuid'):
  530. self.uuid = uuid.uuid4()
  531. # Initialize VM image storage class;
  532. # it might be already initialized by a recursive call from a child VM
  533. if self.storage is None:
  534. self.storage = qubes.storage.Storage(self)
  535. if not self.app.vmm.offline_mode and self.is_running():
  536. self.start_qdb_watch()
  537. @qubes.events.handler('property-set:label')
  538. def on_property_set_label(self, event, name, newvalue, oldvalue=None):
  539. # pylint: disable=unused-argument
  540. if self.icon_path:
  541. try:
  542. os.remove(self.icon_path)
  543. except OSError:
  544. pass
  545. if hasattr(os, "symlink"):
  546. os.symlink(newvalue.icon_path, self.icon_path)
  547. subprocess.call(['sudo', 'xdg-icon-resource', 'forceupdate'])
  548. else:
  549. shutil.copy(newvalue.icon_path, self.icon_path)
  550. @qubes.events.handler('property-pre-set:kernel')
  551. def on_property_pre_set_kernel(self, event, name, newvalue, oldvalue=None):
  552. # pylint: disable=unused-argument
  553. if not newvalue:
  554. return
  555. dirname = os.path.join(
  556. qubes.config.qubes_base_dir,
  557. qubes.config.system_path['qubes_kernels_base_dir'],
  558. newvalue)
  559. if not os.path.exists(dirname):
  560. raise qubes.exc.QubesPropertyValueError(self,
  561. self.property_get_def(name), newvalue,
  562. 'Kernel {!r} not installed'.format(newvalue))
  563. for filename in ('vmlinuz', 'initramfs'):
  564. if not os.path.exists(os.path.join(dirname, filename)):
  565. raise qubes.exc.QubesPropertyValueError(self,
  566. self.property_get_def(name), newvalue,
  567. 'Kernel {!r} not properly installed: '
  568. 'missing {!r} file'.format(newvalue, filename))
  569. @qubes.events.handler('property-pre-set:autostart')
  570. def on_property_pre_set_autostart(self, event, name, newvalue,
  571. oldvalue=None):
  572. # pylint: disable=unused-argument
  573. # workaround https://bugzilla.redhat.com/show_bug.cgi?id=1181922
  574. if newvalue:
  575. retcode = subprocess.call(
  576. ["sudo", "ln", "-sf",
  577. "/usr/lib/systemd/system/qubes-vm@.service",
  578. "/etc/systemd/system/multi-user.target.wants/qubes-vm@"
  579. "{}.service".format(self.name)])
  580. else:
  581. retcode = subprocess.call(
  582. ['sudo', 'systemctl', 'disable',
  583. 'qubes-vm@{}.service'.format(self.name)])
  584. if retcode:
  585. raise qubes.exc.QubesException(
  586. 'Failed to set autostart for VM in systemd')
  587. @qubes.events.handler('property-pre-del:autostart')
  588. def on_property_pre_del_autostart(self, event, name, oldvalue=None):
  589. # pylint: disable=unused-argument
  590. if oldvalue:
  591. retcode = subprocess.call(
  592. ['sudo', 'systemctl', 'disable',
  593. 'qubes-vm@{}.service'.format(self.name)])
  594. if retcode:
  595. raise qubes.exc.QubesException(
  596. 'Failed to reset autostart for VM in systemd')
  597. #
  598. # methods for changing domain state
  599. #
  600. @asyncio.coroutine
  601. def start(self, start_guid=True, notify_function=None,
  602. mem_required=None):
  603. '''Start domain
  604. :param bool start_guid: FIXME
  605. :param collections.Callable notify_function: FIXME
  606. :param int mem_required: FIXME
  607. '''
  608. with (yield from self.startup_lock):
  609. # Intentionally not used is_running(): eliminate also "Paused",
  610. # "Crashed", "Halting"
  611. if self.get_power_state() != 'Halted':
  612. return
  613. self.log.info('Starting {}'.format(self.name))
  614. yield from self.fire_event_async('domain-pre-start',
  615. pre_event=True,
  616. start_guid=start_guid, mem_required=mem_required)
  617. try:
  618. yield from self.storage.verify()
  619. if self.netvm is not None:
  620. # pylint: disable = no-member
  621. if self.netvm.qid != 0:
  622. if not self.netvm.is_running():
  623. yield from self.netvm.start(start_guid=start_guid,
  624. notify_function=notify_function)
  625. qmemman_client = yield from asyncio.get_event_loop().\
  626. run_in_executor(None, self.request_memory, mem_required)
  627. except Exception as exc:
  628. # let anyone receiving domain-pre-start know that startup failed
  629. yield from self.fire_event_async('domain-start-failed',
  630. reason=str(exc))
  631. raise
  632. try:
  633. yield from self.storage.start()
  634. self._update_libvirt_domain()
  635. self.libvirt_domain.createWithFlags(
  636. libvirt.VIR_DOMAIN_START_PAUSED)
  637. except Exception as exc:
  638. # let anyone receiving domain-pre-start know that startup failed
  639. yield from self.fire_event_async('domain-start-failed',
  640. reason=str(exc))
  641. raise
  642. finally:
  643. if qmemman_client:
  644. qmemman_client.close()
  645. try:
  646. yield from self.fire_event_async('domain-spawn',
  647. start_guid=start_guid)
  648. self.log.info('Setting Qubes DB info for the VM')
  649. yield from self.start_qubesdb()
  650. self.create_qdb_entries()
  651. self.start_qdb_watch()
  652. self.log.warning('Activating the {} VM'.format(self.name))
  653. self.libvirt_domain.resume()
  654. yield from self.start_qrexec_daemon()
  655. yield from self.fire_event_async('domain-start',
  656. start_guid=start_guid)
  657. except Exception as exc: # pylint: disable=bare-except
  658. if self.is_running() or self.is_paused():
  659. # This avoids losing the exception if an exception is
  660. # raised in self.force_shutdown(), because the vm is not
  661. # running or paused
  662. yield from self.kill() # pylint: disable=not-an-iterable
  663. # let anyone receiving domain-pre-start know that startup failed
  664. yield from self.fire_event_async('domain-start-failed',
  665. reason=str(exc))
  666. raise
  667. return self
  668. @asyncio.coroutine
  669. def on_domain_shutdown_coro(self):
  670. '''Coroutine for executing cleanup after domain shutdown.
  671. Do not allow domain to be started again until this finishes.
  672. '''
  673. with (yield from self.startup_lock):
  674. try:
  675. yield from self.storage.stop()
  676. except qubes.storage.StoragePoolException:
  677. self.log.exception('Failed to stop storage for domain %s',
  678. self.name)
  679. @qubes.events.handler('domain-shutdown')
  680. def on_domain_shutdown(self, _event, **_kwargs):
  681. '''Cleanup after domain shutdown'''
  682. # TODO: ensure that domain haven't been started _before_ this
  683. # coroutine got a chance to acquire a lock
  684. asyncio.ensure_future(self.on_domain_shutdown_coro())
  685. @asyncio.coroutine
  686. def shutdown(self, force=False, wait=False):
  687. '''Shutdown domain.
  688. :raises qubes.exc.QubesVMNotStartedError: \
  689. when domain is already shut down.
  690. '''
  691. if self.is_halted():
  692. raise qubes.exc.QubesVMNotStartedError(self)
  693. yield from self.fire_event_async('domain-pre-shutdown', pre_event=True,
  694. force=force)
  695. self.libvirt_domain.shutdown()
  696. while wait and not self.is_halted():
  697. yield from asyncio.sleep(0.25)
  698. return self
  699. @asyncio.coroutine
  700. def kill(self):
  701. '''Forcefuly shutdown (destroy) domain.
  702. :raises qubes.exc.QubesVMNotStartedError: \
  703. when domain is already shut down.
  704. '''
  705. if not self.is_running() and not self.is_paused():
  706. raise qubes.exc.QubesVMNotStartedError(self)
  707. self.libvirt_domain.destroy()
  708. return self
  709. def force_shutdown(self, *args, **kwargs):
  710. '''Deprecated alias for :py:meth:`kill`'''
  711. warnings.warn(
  712. 'Call to deprecated function force_shutdown(), use kill() instead',
  713. DeprecationWarning, stacklevel=2)
  714. return self.kill(*args, **kwargs)
  715. @asyncio.coroutine
  716. def suspend(self):
  717. '''Suspend (pause) domain.
  718. :raises qubes.exc.QubesVMNotRunnignError: \
  719. when domain is already shut down.
  720. '''
  721. if not self.is_running() and not self.is_paused():
  722. raise qubes.exc.QubesVMNotRunningError(self)
  723. if list(self.devices['pci'].attached()):
  724. yield from self.run_service_for_stdio('qubes.SuspendPre',
  725. user='root')
  726. self.libvirt_domain.pMSuspendForDuration(
  727. libvirt.VIR_NODE_SUSPEND_TARGET_MEM, 0, 0)
  728. else:
  729. self.libvirt_domain.suspend()
  730. return self
  731. @asyncio.coroutine
  732. def pause(self):
  733. '''Pause (suspend) domain.'''
  734. if not self.is_running():
  735. raise qubes.exc.QubesVMNotRunningError(self)
  736. self.libvirt_domain.suspend()
  737. return self
  738. @asyncio.coroutine
  739. def resume(self):
  740. '''Resume suspended domain.
  741. :raises qubes.exc.QubesVMNotSuspendedError: when machine is not paused
  742. :raises qubes.exc.QubesVMError: when machine is suspended
  743. '''
  744. # pylint: disable=not-an-iterable
  745. if self.get_power_state() == "Suspended":
  746. self.libvirt_domain.pMWakeup()
  747. yield from self.run_service_for_stdio('qubes.SuspendPost',
  748. user='root')
  749. else:
  750. yield from self.unpause()
  751. return self
  752. @asyncio.coroutine
  753. def unpause(self):
  754. '''Resume (unpause) a domain'''
  755. if not self.is_paused():
  756. raise qubes.exc.QubesVMNotPausedError(self)
  757. self.libvirt_domain.resume()
  758. return self
  759. @asyncio.coroutine
  760. def run_service(self, service, source=None, user=None,
  761. filter_esc=False, autostart=False, gui=False, **kwargs):
  762. '''Run service on this VM
  763. :param str service: service name
  764. :param qubes.vm.qubesvm.QubesVM source: source domain as presented to
  765. this VM
  766. :param str user: username to run service as
  767. :param bool filter_esc: filter escape sequences to protect terminal \
  768. emulator
  769. :param bool autostart: if :py:obj:`True`, machine will be started if \
  770. it is not running
  771. :param bool gui: when autostarting, also start gui daemon
  772. :rtype: asyncio.subprocess.Process
  773. .. note::
  774. User ``root`` is redefined to ``SYSTEM`` in the Windows agent code
  775. '''
  776. # UNSUPPORTED from previous incarnation:
  777. # localcmd, wait, passio*, notify_function, `-e` switch
  778. #
  779. # - passio* and friends depend on params to command (like in stdlib)
  780. # - the filter_esc is orthogonal to passio*
  781. # - input: see run_service_for_stdio
  782. # - wait has no purpose since this is asynchronous
  783. # - notify_function is gone
  784. source = 'dom0' if source is None else self.app.domains[source].name
  785. if user is None:
  786. user = self.default_user
  787. if self.is_paused():
  788. # XXX what about autostart?
  789. raise qubes.exc.QubesVMNotRunningError(
  790. self, 'Domain {!r} is paused'.format(self.name))
  791. elif not self.is_running():
  792. if not autostart:
  793. raise qubes.exc.QubesVMNotRunningError(self)
  794. yield from self.start(start_guid=gui)
  795. if not self.is_qrexec_running():
  796. raise qubes.exc.QubesVMError(
  797. self, 'Domain {!r}: qrexec not connected'.format(self.name))
  798. yield from self.fire_event_async('domain-cmd-pre-run', pre_event=True,
  799. start_guid=gui)
  800. return (yield from asyncio.create_subprocess_exec(
  801. qubes.config.system_path['qrexec_client_path'],
  802. '-d', str(self.name),
  803. *(('-t', '-T') if filter_esc else ()),
  804. '{}:QUBESRPC {} {}'.format(user, service, source),
  805. **kwargs))
  806. @asyncio.coroutine
  807. def run_service_for_stdio(self, *args, input=None, **kwargs):
  808. '''Run a service, pass an optional input and return (stdout, stderr).
  809. Raises an exception if return code != 0.
  810. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  811. .. warning::
  812. There are some combinations if stdio-related *kwargs*, which are
  813. not filtered for problems originating between the keyboard and the
  814. chair.
  815. ''' # pylint: disable=redefined-builtin
  816. kwargs.setdefault('stdin', subprocess.PIPE)
  817. kwargs.setdefault('stdout', subprocess.PIPE)
  818. kwargs.setdefault('stderr', subprocess.PIPE)
  819. p = yield from self.run_service(*args, **kwargs)
  820. # this one is actually a tuple, but there is no need to unpack it
  821. stdouterr = yield from p.communicate(input=input)
  822. if p.returncode:
  823. raise subprocess.CalledProcessError(p.returncode,
  824. args[0], *stdouterr)
  825. return stdouterr
  826. @staticmethod
  827. def _prepare_input_for_vmshell(command, input):
  828. '''Prepare shell input for the given command and optional (real) input
  829. ''' # pylint: disable=redefined-builtin
  830. if input is None:
  831. input = b''
  832. return b''.join((command.rstrip('\n').encode('utf-8'), b'\n', input))
  833. def run(self, command, user=None, **kwargs):
  834. '''Run a shell command inside the domain using qrexec.
  835. This method is a coroutine.
  836. ''' # pylint: disable=redefined-builtin
  837. if user is None:
  838. user = self.default_user
  839. return asyncio.create_subprocess_exec(
  840. qubes.config.system_path['qrexec_client_path'],
  841. '-d', str(self.name),
  842. '{}:{}'.format(user, command),
  843. **kwargs)
  844. @asyncio.coroutine
  845. def run_for_stdio(self, *args, input=None, **kwargs):
  846. '''Run a shell command inside the domain using qubes.VMShell qrexec.
  847. This method is a coroutine.
  848. *kwargs* are passed verbatim to :py:meth:`run_service_for_stdio`.
  849. See disclaimer there.
  850. ''' # pylint: disable=redefined-builtin
  851. kwargs.setdefault('stdin', subprocess.PIPE)
  852. kwargs.setdefault('stdout', subprocess.PIPE)
  853. kwargs.setdefault('stderr', subprocess.PIPE)
  854. p = yield from self.run(*args, **kwargs)
  855. stdouterr = yield from p.communicate(input=input)
  856. if p.returncode:
  857. raise subprocess.CalledProcessError(p.returncode,
  858. args[0], *stdouterr)
  859. return stdouterr
  860. def request_memory(self, mem_required=None):
  861. # overhead of per-qube/per-vcpu Xen structures,
  862. # taken from OpenStack nova/virt/xenapi/driver.py
  863. # see https://wiki.openstack.org/wiki/XenServer/Overhead
  864. # add an extra MB because Nova rounds up to MBs
  865. if not qmemman_present:
  866. return
  867. if mem_required is None:
  868. if self.virt_mode == 'hvm':
  869. if self.stubdom_mem:
  870. stubdom_mem = self.stubdom_mem
  871. else:
  872. if self.features.check_with_template('linux-stubdom', True):
  873. stubdom_mem = 128 # from libxl_create.c
  874. else:
  875. stubdom_mem = 28 # from libxl_create.c
  876. stubdom_mem += 16 # video ram
  877. else:
  878. stubdom_mem = 0
  879. mem_required = int(self.memory + stubdom_mem) * 1024 * 1024
  880. qmemman_client = qubes.qmemman.client.QMemmanClient()
  881. try:
  882. mem_required_with_overhead = mem_required + MEM_OVERHEAD_BASE \
  883. + self.vcpus * MEM_OVERHEAD_PER_VCPU
  884. got_memory = qmemman_client.request_memory(
  885. mem_required_with_overhead)
  886. except IOError as e:
  887. raise IOError('Failed to connect to qmemman: {!s}'.format(e))
  888. if not got_memory:
  889. qmemman_client.close()
  890. raise qubes.exc.QubesMemoryError(self)
  891. return qmemman_client
  892. @staticmethod
  893. @asyncio.coroutine
  894. def start_daemon(*command, input=None, **kwargs):
  895. '''Start a daemon for the VM
  896. This function take care to run it as appropriate user.
  897. :param command: command to run (array for
  898. :py:meth:`subprocess.check_call`)
  899. :param kwargs: args for :py:meth:`subprocess.check_call`
  900. :return: None
  901. ''' # pylint: disable=redefined-builtin
  902. if os.getuid() == 0:
  903. # try to always have VM daemons running as normal user, otherwise
  904. # some files (like clipboard) may be created as root and cause
  905. # permission problems
  906. qubes_group = grp.getgrnam('qubes')
  907. command = ['runuser', '-u', qubes_group.gr_mem[0], '--'] + \
  908. list(command)
  909. p = yield from asyncio.create_subprocess_exec(*command, **kwargs)
  910. stdout, stderr = yield from p.communicate(input=input)
  911. if p.returncode:
  912. raise subprocess.CalledProcessError(p.returncode, command,
  913. output=stdout, stderr=stderr)
  914. @asyncio.coroutine
  915. def start_qrexec_daemon(self):
  916. '''Start qrexec daemon.
  917. :raises OSError: when starting fails.
  918. '''
  919. self.log.debug('Starting the qrexec daemon')
  920. qrexec_args = [str(self.xid), self.name, self.default_user]
  921. if not self.debug:
  922. qrexec_args.insert(0, "-q")
  923. qrexec_env = os.environ.copy()
  924. if not self.features.check_with_template('qrexec', False):
  925. self.log.debug(
  926. 'Starting the qrexec daemon in background, because of features')
  927. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  928. else:
  929. qrexec_env['QREXEC_STARTUP_TIMEOUT'] = str(self.qrexec_timeout)
  930. try:
  931. yield from self.start_daemon(
  932. qubes.config.system_path['qrexec_daemon_path'], *qrexec_args,
  933. env=qrexec_env)
  934. except subprocess.CalledProcessError:
  935. raise qubes.exc.QubesVMError(self, 'Cannot execute qrexec-daemon!')
  936. @asyncio.coroutine
  937. def start_qubesdb(self):
  938. '''Start QubesDB daemon.
  939. :raises OSError: when starting fails.
  940. '''
  941. # drop old connection to QubesDB, if any
  942. self._qdb_connection = None
  943. self.log.info('Starting Qubes DB')
  944. try:
  945. yield from self.start_daemon(
  946. qubes.config.system_path['qubesdb_daemon_path'],
  947. str(self.xid),
  948. self.name)
  949. except subprocess.CalledProcessError:
  950. raise qubes.exc.QubesException('Cannot execute qubesdb-daemon')
  951. @asyncio.coroutine
  952. def create_on_disk(self, pool=None, pools=None):
  953. '''Create files needed for VM.
  954. '''
  955. self.log.info('Creating directory: {0}'.format(self.dir_path))
  956. os.makedirs(self.dir_path, mode=0o775)
  957. if pool or pools:
  958. # pylint: disable=attribute-defined-outside-init
  959. self.volume_config = _patch_volume_config(self.volume_config, pool,
  960. pools)
  961. self.storage = qubes.storage.Storage(self)
  962. try:
  963. yield from self.storage.create()
  964. except:
  965. try:
  966. yield from self.storage.remove()
  967. os.rmdir(self.dir_path)
  968. except: # pylint: disable=bare-except
  969. self.log.exception('failed to cleanup {} after failed VM '
  970. 'creation'.format(self.dir_path))
  971. raise
  972. self.log.info('Creating icon symlink: {} -> {}'.format(
  973. self.icon_path, self.label.icon_path))
  974. if hasattr(os, "symlink"):
  975. os.symlink(self.label.icon_path, self.icon_path)
  976. else:
  977. shutil.copy(self.label.icon_path, self.icon_path)
  978. # fire hooks
  979. yield from self.fire_event_async('domain-create-on-disk')
  980. @asyncio.coroutine
  981. def remove_from_disk(self):
  982. '''Remove domain remnants from disk.'''
  983. if not self.is_halted():
  984. raise qubes.exc.QubesVMNotHaltedError(
  985. "Can't remove VM {!s}, beacuse it's in state {!r}.".format(
  986. self, self.get_power_state()))
  987. yield from self.fire_event_async('domain-remove-from-disk')
  988. try:
  989. # TODO: make it async?
  990. shutil.rmtree(self.dir_path)
  991. except OSError as e:
  992. if e.errno == errno.ENOENT:
  993. pass
  994. else:
  995. raise
  996. yield from self.storage.remove()
  997. @asyncio.coroutine
  998. def clone_disk_files(self, src, pool=None, pools=None, ):
  999. '''Clone files from other vm.
  1000. :param qubes.vm.qubesvm.QubesVM src: source VM
  1001. '''
  1002. # If the current vm name is not a part of `self.app.domains.keys()`,
  1003. # then the current vm is in creation process. Calling
  1004. # `self.is_halted()` at this point, would instantiate libvirt, we want
  1005. # avoid that.
  1006. if self.name in self.app.domains.keys() and not self.is_halted():
  1007. raise qubes.exc.QubesVMNotHaltedError(
  1008. self, 'Cannot clone a running domain {!r}'.format(self.name))
  1009. msg = "Destination {!s} already exists".format(self.dir_path)
  1010. assert not os.path.exists(self.dir_path), msg
  1011. self.log.info('Creating directory: {0}'.format(self.dir_path))
  1012. os.makedirs(self.dir_path, mode=0o775)
  1013. if pool or pools:
  1014. # pylint: disable=attribute-defined-outside-init
  1015. self.volume_config = _patch_volume_config(self.volume_config, pool,
  1016. pools)
  1017. self.storage = qubes.storage.Storage(self)
  1018. yield from self.storage.clone(src)
  1019. self.storage.verify()
  1020. assert self.volumes != {}
  1021. if src.icon_path is not None \
  1022. and os.path.exists(src.dir_path) \
  1023. and self.icon_path is not None:
  1024. if os.path.islink(src.icon_path):
  1025. icon_path = os.readlink(src.icon_path)
  1026. self.log.info(
  1027. 'Creating icon symlink {} -> {}'.format(
  1028. self.icon_path, icon_path))
  1029. os.symlink(icon_path, self.icon_path)
  1030. else:
  1031. self.log.info(
  1032. 'Copying icon {} -> {}'.format(
  1033. src.icon_path, self.icon_path))
  1034. shutil.copy(src.icon_path, self.icon_path)
  1035. # fire hooks
  1036. yield from self.fire_event_async('domain-clone-files', src=src)
  1037. #
  1038. # methods for querying domain state
  1039. #
  1040. # state of the machine
  1041. def get_power_state(self):
  1042. '''Return power state description string.
  1043. Return value may be one of those:
  1044. =============== ========================================================
  1045. return value meaning
  1046. =============== ========================================================
  1047. ``'Halted'`` Machine is not active.
  1048. ``'Transient'`` Machine is running, but does not have :program:`guid`
  1049. or :program:`qrexec` available.
  1050. ``'Running'`` Machine is ready and running.
  1051. ``'Paused'`` Machine is paused.
  1052. ``'Suspended'`` Machine is S3-suspended.
  1053. ``'Halting'`` Machine is in process of shutting down.
  1054. ``'Dying'`` Machine crashed and is unusable.
  1055. ``'Crashed'`` Machine crashed and is unusable, probably because of
  1056. bug in dom0.
  1057. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  1058. is undefined).
  1059. =============== ========================================================
  1060. FIXME: graph below may be incomplete and wrong. Click on method name to
  1061. see its documentation.
  1062. .. graphviz::
  1063. digraph {
  1064. node [fontname="sans-serif"];
  1065. edge [fontname="mono"];
  1066. Halted;
  1067. NA;
  1068. Dying;
  1069. Crashed;
  1070. Transient;
  1071. Halting;
  1072. Running;
  1073. Paused [color=gray75 fontcolor=gray75];
  1074. Suspended;
  1075. NA -> Halted;
  1076. Halted -> NA [constraint=false];
  1077. Halted -> Transient
  1078. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  1079. Transient -> Running;
  1080. Running -> Halting
  1081. [xlabel="shutdown()"
  1082. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  1083. constraint=false];
  1084. Halting -> Dying -> Halted [constraint=false];
  1085. /* cosmetic, invisible edges to put rank constraint */
  1086. Dying -> Halting [style="invis"];
  1087. Halting -> Transient [style="invis"];
  1088. Running -> Halted
  1089. [label="force_shutdown()"
  1090. URL="#qubes.vm.qubesvm.QubesVM.force_shutdown"
  1091. constraint=false];
  1092. Running -> Crashed [constraint=false];
  1093. Crashed -> Halted [constraint=false];
  1094. Running -> Paused
  1095. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  1096. color=gray75 fontcolor=gray75];
  1097. Running -> Suspended
  1098. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"
  1099. color=gray50 fontcolor=gray50];
  1100. Paused -> Running
  1101. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  1102. color=gray75 fontcolor=gray75];
  1103. Suspended -> Running
  1104. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"
  1105. color=gray50 fontcolor=gray50];
  1106. Running -> Suspended
  1107. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  1108. Suspended -> Running
  1109. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  1110. { rank=source; Halted NA };
  1111. { rank=same; Transient Halting };
  1112. { rank=same; Crashed Dying };
  1113. { rank=sink; Paused Suspended };
  1114. }
  1115. .. seealso::
  1116. http://wiki.libvirt.org/page/VM_lifecycle
  1117. Description of VM life cycle from the point of view of libvirt.
  1118. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  1119. Libvirt's enum describing precise state of a domain.
  1120. ''' # pylint: disable=too-many-return-statements
  1121. # don't try to define libvirt domain, if it isn't there, VM surely
  1122. # isn't running
  1123. # reason for this "if": allow vm.is_running() in PCI (or other
  1124. # device) extension while constructing libvirt XML
  1125. if self.app.vmm.offline_mode:
  1126. return 'Halted'
  1127. if self._libvirt_domain is None:
  1128. try:
  1129. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  1130. self.uuid.bytes)
  1131. except libvirt.libvirtError as e:
  1132. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1133. return 'Halted'
  1134. else:
  1135. raise
  1136. libvirt_domain = self.libvirt_domain
  1137. if libvirt_domain is None:
  1138. return 'Halted'
  1139. try:
  1140. if libvirt_domain.isActive():
  1141. # pylint: disable=line-too-long
  1142. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  1143. return "Paused"
  1144. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  1145. return "Crashed"
  1146. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  1147. return "Halting"
  1148. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  1149. return "Dying"
  1150. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED: # nopep8
  1151. return "Suspended"
  1152. else:
  1153. if not self.is_fully_usable():
  1154. return "Transient"
  1155. return "Running"
  1156. return 'Halted'
  1157. except libvirt.libvirtError as e:
  1158. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1159. return 'Halted'
  1160. raise
  1161. assert False
  1162. def is_halted(self):
  1163. ''' Check whether this domain's state is 'Halted'
  1164. :returns: :py:obj:`True` if this domain is halted, \
  1165. :py:obj:`False` otherwise.
  1166. :rtype: bool
  1167. '''
  1168. return self.get_power_state() == 'Halted'
  1169. def is_running(self):
  1170. '''Check whether this domain is running.
  1171. :returns: :py:obj:`True` if this domain is started, \
  1172. :py:obj:`False` otherwise.
  1173. :rtype: bool
  1174. '''
  1175. if self.app.vmm.offline_mode:
  1176. return False
  1177. # don't try to define libvirt domain, if it isn't there, VM surely
  1178. # isn't running
  1179. # reason for this "if": allow vm.is_running() in PCI (or other
  1180. # device) extension while constructing libvirt XML
  1181. if self._libvirt_domain is None:
  1182. try:
  1183. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  1184. self.uuid.bytes)
  1185. except libvirt.libvirtError as e:
  1186. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1187. return False
  1188. else:
  1189. raise
  1190. return self.libvirt_domain.isActive()
  1191. def is_paused(self):
  1192. '''Check whether this domain is paused.
  1193. :returns: :py:obj:`True` if this domain is paused, \
  1194. :py:obj:`False` otherwise.
  1195. :rtype: bool
  1196. '''
  1197. return self.libvirt_domain \
  1198. and self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED
  1199. def is_qrexec_running(self):
  1200. '''Check whether qrexec for this domain is available.
  1201. :returns: :py:obj:`True` if qrexec is running, \
  1202. :py:obj:`False` otherwise.
  1203. :rtype: bool
  1204. '''
  1205. if self.xid < 0:
  1206. return False
  1207. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1208. def is_fully_usable(self):
  1209. return all(self.fire_event('domain-is-fully-usable'))
  1210. @qubes.events.handler('domain-is-fully-usable')
  1211. def on_domain_is_fully_usable(self, event):
  1212. '''Check whether domain is running and sane.
  1213. Currently this checks for running qrexec.
  1214. ''' # pylint: disable=unused-argument
  1215. # Running gui-daemon implies also VM running
  1216. if not self.is_qrexec_running():
  1217. yield False
  1218. # memory and disk
  1219. def get_mem(self):
  1220. '''Get current memory usage from VM.
  1221. :returns: Memory usage [FIXME unit].
  1222. :rtype: FIXME
  1223. '''
  1224. if self.libvirt_domain is None:
  1225. return 0
  1226. try:
  1227. if not self.libvirt_domain.isActive():
  1228. return 0
  1229. return self.libvirt_domain.info()[1]
  1230. except libvirt.libvirtError as e:
  1231. if e.get_error_code() in (
  1232. # qube no longer exists
  1233. libvirt.VIR_ERR_NO_DOMAIN,
  1234. # libxl_domain_info failed (race condition from isActive)
  1235. libvirt.VIR_ERR_INTERNAL_ERROR):
  1236. return 0
  1237. else:
  1238. self.log.exception(
  1239. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1240. raise
  1241. def get_mem_static_max(self):
  1242. '''Get maximum memory available to VM.
  1243. :returns: Memory limit [FIXME unit].
  1244. :rtype: FIXME
  1245. '''
  1246. if self.libvirt_domain is None:
  1247. return 0
  1248. try:
  1249. return self.libvirt_domain.maxMemory()
  1250. except libvirt.libvirtError as e:
  1251. if e.get_error_code() in (
  1252. # qube no longer exists
  1253. libvirt.VIR_ERR_NO_DOMAIN,
  1254. # libxl_domain_info failed (race condition from isActive)
  1255. libvirt.VIR_ERR_INTERNAL_ERROR):
  1256. return 0
  1257. else:
  1258. self.log.exception(
  1259. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1260. raise
  1261. def get_cputime(self):
  1262. '''Get total CPU time burned by this domain since start.
  1263. :returns: CPU time usage [FIXME unit].
  1264. :rtype: FIXME
  1265. '''
  1266. if self.libvirt_domain is None:
  1267. return 0
  1268. if self.libvirt_domain is None:
  1269. return 0
  1270. if not self.libvirt_domain.isActive():
  1271. return 0
  1272. try:
  1273. if not self.libvirt_domain.isActive():
  1274. return 0
  1275. # this does not work, because libvirt
  1276. # return self.libvirt_domain.getCPUStats(
  1277. # libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1278. return self.libvirt_domain.info()[4]
  1279. except libvirt.libvirtError as e:
  1280. if e.get_error_code() in (
  1281. # qube no longer exists
  1282. libvirt.VIR_ERR_NO_DOMAIN,
  1283. # libxl_domain_info failed (race condition from isActive)
  1284. libvirt.VIR_ERR_INTERNAL_ERROR):
  1285. return 0
  1286. else:
  1287. self.log.exception(
  1288. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1289. raise
  1290. # miscellanous
  1291. def get_start_time(self):
  1292. '''Tell when machine was started.
  1293. :rtype: datetime.datetime
  1294. '''
  1295. if not self.is_running():
  1296. return None
  1297. # TODO shouldn't this be qubesdb?
  1298. start_time = self.app.vmm.xs.read('',
  1299. '/vm/{}/start_time'.format(self.uuid))
  1300. if start_time != '':
  1301. return datetime.datetime.fromtimestamp(float(start_time))
  1302. return None
  1303. #
  1304. # helper methods
  1305. #
  1306. def relative_path(self, path):
  1307. '''Return path relative to py:attr:`dir_path`.
  1308. :param str path: Path in question.
  1309. :returns: Relative path.
  1310. '''
  1311. return os.path.relpath(path, self.dir_path)
  1312. def create_qdb_entries(self):
  1313. '''Create entries in Qubes DB.
  1314. '''
  1315. # pylint: disable=no-member
  1316. self.untrusted_qdb.write('/name', self.name)
  1317. self.untrusted_qdb.write('/type', self.__class__.__name__)
  1318. self.untrusted_qdb.write('/qubes-vm-updateable', str(self.updateable))
  1319. self.untrusted_qdb.write('/qubes-vm-persistence',
  1320. 'full' if self.updateable else 'rw-only')
  1321. self.untrusted_qdb.write('/qubes-debug-mode', str(int(self.debug)))
  1322. try:
  1323. self.untrusted_qdb.write('/qubes-base-template', self.template.name)
  1324. except AttributeError:
  1325. self.untrusted_qdb.write('/qubes-base-template', '')
  1326. self.untrusted_qdb.write('/qubes-random-seed',
  1327. base64.b64encode(qubes.utils.urandom(64)))
  1328. if self.provides_network:
  1329. # '/qubes-netvm-network' value is only checked for being non empty
  1330. self.untrusted_qdb.write('/qubes-netvm-network', self.gateway)
  1331. self.untrusted_qdb.write('/qubes-netvm-gateway', self.gateway)
  1332. self.untrusted_qdb.write('/qubes-netvm-netmask', self.netmask)
  1333. for i, addr in zip(('primary', 'secondary'), self.dns):
  1334. self.untrusted_qdb.write('/qubes-netvm-{}-dns'.format(i), addr)
  1335. if self.netvm is not None:
  1336. self.untrusted_qdb.write('/qubes-ip', self.visible_ip)
  1337. self.untrusted_qdb.write('/qubes-netmask', self.visible_netmask)
  1338. self.untrusted_qdb.write('/qubes-gateway', self.visible_gateway)
  1339. for i, addr in zip(('primary', 'secondary'), self.dns):
  1340. self.untrusted_qdb.write('/qubes-{}-dns'.format(i), addr)
  1341. tzname = qubes.utils.get_timezone()
  1342. if tzname:
  1343. self.untrusted_qdb.write('/qubes-timezone', tzname)
  1344. self.untrusted_qdb.write('/qubes-block-devices', '')
  1345. self.untrusted_qdb.write('/qubes-usb-devices', '')
  1346. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1347. # xenstore for it until decided otherwise
  1348. if qmemman_present:
  1349. self.app.vmm.xs.set_permissions('',
  1350. '/local/domain/{}/memory'.format(self.xid),
  1351. [{'dom': self.xid}])
  1352. self.fire_event('domain-qdb-create')
  1353. # TODO async; update this in constructor
  1354. def _update_libvirt_domain(self):
  1355. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1356. domain_config = self.create_config_file()
  1357. try:
  1358. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1359. domain_config)
  1360. except libvirt.libvirtError as e:
  1361. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1362. and e.get_str2() == 'hvm':
  1363. raise qubes.exc.QubesVMError(self,
  1364. 'HVM qubes are not supported on this machine. '
  1365. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1366. else:
  1367. raise
  1368. #
  1369. # workshop -- those are to be reworked later
  1370. #
  1371. def get_prefmem(self):
  1372. # TODO: qmemman is still xen specific
  1373. untrusted_meminfo_key = self.app.vmm.xs.read('',
  1374. '/local/domain/{}/memory/meminfo'.format(self.xid))
  1375. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1376. return 0
  1377. domain = qubes.qmemman.DomainState(self.xid)
  1378. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1379. domain, untrusted_meminfo_key)
  1380. if domain.mem_used is None:
  1381. # apparently invalid xenstore content
  1382. return 0
  1383. domain.memory_maximum = self.get_mem_static_max() * 1024
  1384. return qubes.qmemman.algo.prefmem(domain) / 1024
  1385. def _clean_volume_config(config):
  1386. common_attributes = ['name', 'pool', 'size',
  1387. 'revisions_to_keep', 'rw', 'snap_on_start',
  1388. 'save_on_stop', 'source']
  1389. return {k: v for k, v in config.items() if k in common_attributes}
  1390. def _patch_pool_config(config, pool=None, pools=None):
  1391. assert pool is not None or pools is not None
  1392. is_snapshot = config['snap_on_start']
  1393. is_rw = config['rw']
  1394. name = config['name']
  1395. if pool and not is_snapshot and is_rw:
  1396. config['pool'] = str(pool)
  1397. elif pool:
  1398. pass
  1399. elif pools and name in pools.keys():
  1400. if not is_snapshot:
  1401. config['pool'] = str(pools[name])
  1402. else:
  1403. msg = "Can't clone a snapshot volume {!s} to pool {!s} " \
  1404. .format(name, pools[name])
  1405. raise qubes.exc.QubesException(msg)
  1406. return config
  1407. def _patch_volume_config(volume_config, pool=None, pools=None):
  1408. assert not (pool and pools), \
  1409. 'You can not pass pool & pools parameter at same time'
  1410. assert pool or pools
  1411. result = {}
  1412. for name, config in volume_config.items():
  1413. # copy only the subset of volume_config key/values
  1414. dst_config = _clean_volume_config(config)
  1415. if pool is not None or pools is not None:
  1416. dst_config = _patch_pool_config(dst_config, pool, pools)
  1417. result[name] = dst_config
  1418. return result