qubesvm.py 62 KB

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