qubesvm.py 65 KB

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