qubesvm.py 66 KB

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