qubesvm.py 66 KB

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