qubesvm.py 61 KB

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