qubesvm.py 59 KB

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