qubesvm.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  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 os
  30. import os.path
  31. import pipes
  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: self.storage.vmdir),
  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 qdb(self):
  277. '''QubesDB handle for this domain.'''
  278. if self._qdb_connection is None:
  279. if self.is_running():
  280. import qubesdb
  281. self._qdb_connection = qubesdb.QubesDB(self.name)
  282. return self._qdb_connection
  283. # XXX this should go to to AppVM?
  284. @property
  285. def private_img(self):
  286. '''Location of private image of the VM (that contains :file:`/rw` \
  287. and :file:`/home`).'''
  288. return self.storage.private_img
  289. # XXX this should go to to AppVM? or TemplateVM?
  290. @property
  291. def root_img(self):
  292. '''Location of root image.'''
  293. return self.storage.root_img
  294. # XXX and this should go to exactly where? DispVM has it.
  295. @property
  296. def volatile_img(self):
  297. '''Volatile image that overlays :py:attr:`root_img`.'''
  298. return self.storage.volatile_img
  299. # XXX shouldn't this go elsewhere?
  300. @property
  301. def updateable(self):
  302. '''True if this machine may be updated on its own.'''
  303. return not hasattr(self, 'template')
  304. @property
  305. def icon_path(self):
  306. return os.path.join(self.dir_path, 'icon.png')
  307. @property
  308. def conf_file(self):
  309. return os.path.join(self.dir_path, 'libvirt.xml')
  310. # XXX I don't know what to do with these; probably should be isinstance(...)
  311. def is_template(self):
  312. warnings.warn('vm.is_template() is deprecated, use isinstance()',
  313. DeprecationWarning)
  314. import qubes.vm.templatevm
  315. return isinstance(self, qubes.vm.templatevm.TemplateVM)
  316. def is_appvm(self):
  317. warnings.warn('vm.is_appvm() is deprecated, use isinstance()',
  318. DeprecationWarning)
  319. import qubes.vm.appvm
  320. return isinstance(self, qubes.vm.appvm.AppVM)
  321. def is_proxyvm(self):
  322. warnings.warn('vm.is_proxyvm() is deprecated',
  323. DeprecationWarning)
  324. return self.netvm is not None and self.provides_network
  325. def is_disposablevm(self):
  326. warnings.warn('vm.is_disposable() is deprecated, use isinstance()',
  327. DeprecationWarning)
  328. import qubes.vm.dispvm
  329. return isinstance(self, qubes.vm.dispvm.DispVM)
  330. def is_netvm(self):
  331. warnings.warn('vm.is_netvm() is deprecated, use isinstance()',
  332. DeprecationWarning)
  333. return isinstance(self, qubes.vm.mix.net.NetVMMixin) \
  334. and self.provides_network
  335. # network-related
  336. #
  337. # constructor
  338. #
  339. def __init__(self, app, xml, **kwargs):
  340. super(QubesVM, self).__init__(app, xml, **kwargs)
  341. import qubes.vm.adminvm # pylint: disable=redefined-outer-name
  342. #Init private attrs
  343. self._libvirt_domain = None
  344. self._qdb_connection = None
  345. if xml is None:
  346. # we are creating new VM and attributes came through kwargs
  347. assert hasattr(self, 'qid')
  348. assert hasattr(self, 'name')
  349. # Linux specific cap: max memory can't scale beyond 10.79*init_mem
  350. # see https://groups.google.com/forum/#!topic/qubes-devel/VRqkFj1IOtA
  351. if self.maxmem > self.memory * 10:
  352. self.maxmem = self.memory * 10
  353. # By default allow use all VCPUs
  354. # if not hasattr(self, 'vcpus') and not self.app.vmm.offline_mode:
  355. # self.vcpus = self.app.host.no_cpus
  356. if len(self.devices['pci']) > 0:
  357. # Force meminfo-writer disabled when VM have PCI devices
  358. self.features['meminfo-writer'] = None
  359. elif not isinstance(self, qubes.vm.adminvm.AdminVM) \
  360. and 'meminfo-writer' not in self.features:
  361. # Always set if meminfo-writer should be active or not
  362. self.features['meminfo-writer'] = '1'
  363. if xml is None:
  364. # new qube, disable updates check if requested for new qubes
  365. # TODO: when features (#1637) are done, migrate to plugin
  366. if not self.app.check_updates_vm:
  367. self.features['check-updates'] = None
  368. # will be initialized after loading all the properties
  369. self.storage = None
  370. # fire hooks
  371. if xml is None:
  372. self.events_enabled = True
  373. self.fire_event('domain-init')
  374. #
  375. # event handlers
  376. #
  377. @qubes.events.handler('domain-init', 'domain-load')
  378. def on_domain_init_loaded(self, event):
  379. # pylint: disable=unused-argument
  380. if not hasattr(self, 'uuid'):
  381. self.uuid = uuid.uuid4()
  382. # Initialize VM image storage class
  383. self.storage = qubes.storage.get_pool(
  384. self.pool_name, self).get_storage()
  385. @qubes.events.handler('property-set:label')
  386. def on_property_set_label(self, event, name, new_label, old_label=None):
  387. # pylint: disable=unused-argument
  388. if self.icon_path:
  389. try:
  390. os.remove(self.icon_path)
  391. except OSError:
  392. pass
  393. if hasattr(os, "symlink"):
  394. os.symlink(new_label.icon_path, self.icon_path)
  395. # FIXME: some os-independent wrapper?
  396. subprocess.call(['sudo', 'xdg-icon-resource', 'forceupdate'])
  397. else:
  398. shutil.copy(new_label.icon_path, self.icon_path)
  399. @qubes.events.handler('property-pre-set:name')
  400. def on_property_pre_set_name(self, event, name, newvalue, oldvalue=None):
  401. # pylint: disable=unused-argument
  402. # TODO not self.is_stopped() would be more appropriate
  403. if self.is_running():
  404. raise qubes.exc.QubesVMNotHaltedError(
  405. 'Cannot change name of running domain {!r}'.format(oldvalue))
  406. if self.autostart:
  407. subprocess.check_call(['sudo', 'systemctl', '-q', 'disable',
  408. 'qubes-vm@{}.service'.format(oldvalue)])
  409. try:
  410. self.app.domains[newvalue]
  411. except KeyError:
  412. pass
  413. else:
  414. raise qubes.exc.QubesValueError(
  415. 'VM named {!r} already exists'.format(newvalue))
  416. @qubes.events.handler('property-set:name')
  417. def on_property_set_name(self, event, name, new_name, old_name=None):
  418. # pylint: disable=unused-argument
  419. self.init_log()
  420. if self._libvirt_domain is not None:
  421. self.libvirt_domain.undefine()
  422. self._libvirt_domain = None
  423. if self._qdb_connection is not None:
  424. self._qdb_connection.close()
  425. self._qdb_connection = None
  426. self.storage.rename(
  427. os.path.join(qubes.config.system_path['qubes_base_dir'],
  428. self.dir_path_prefix, new_name),
  429. os.path.join(qubes.config.system_path['qubes_base_dir'],
  430. self.dir_path_prefix, old_name))
  431. self._update_libvirt_domain()
  432. if self.autostart:
  433. self.autostart = self.autostart
  434. @qubes.events.handler('property-pre-set:autostart')
  435. def on_property_pre_set_autostart(self, event, prop, name, value,
  436. oldvalue=None):
  437. # pylint: disable=unused-argument
  438. if subprocess.call(['sudo', 'systemctl',
  439. ('enable' if value else 'disable'),
  440. 'qubes-vm@{}.service'.format(self.name)]):
  441. raise qubes.exc.QubesException(
  442. 'Failed to set autostart for VM via systemctl')
  443. @qubes.events.handler('device-pre-attach:pci')
  444. def on_device_pre_attached_pci(self, event, pci):
  445. # pylint: disable=unused-argument
  446. if not os.path.exists('/sys/bus/pci/devices/0000:{}'.format(pci)):
  447. raise qubes.exc.QubesException('Invalid PCI device: {}'.format(pci))
  448. if not self.is_running():
  449. return
  450. try:
  451. # TODO: libvirt-ise
  452. subprocess.check_call(
  453. ['sudo', qubes.config.system_path['qubes_pciback_cmd'], pci])
  454. subprocess.check_call(
  455. ['sudo', 'xl', 'pci-attach', str(self.xid), pci])
  456. except subprocess.CalledProcessError as e:
  457. self.log.exception('Failed to attach PCI device {!r} on the fly,'
  458. ' changes will be seen after VM restart.'.format(pci), e)
  459. @qubes.events.handler('device-pre-detach:pci')
  460. def on_device_pre_detached_pci(self, event, pci):
  461. # pylint: disable=unused-argument
  462. if not self.is_running():
  463. return
  464. # TODO: libvirt-ise
  465. p = subprocess.Popen(['xl', 'pci-list', str(self.xid)],
  466. stdout=subprocess.PIPE)
  467. result = p.communicate()
  468. m = re.search(r"^(\d+.\d+)\s+0000:%s$" % pci, result[0],
  469. flags=re.MULTILINE)
  470. if not m:
  471. print >>sys.stderr, "Device %s already detached" % pci
  472. return
  473. vmdev = m.group(1)
  474. try:
  475. self.run_service("qubes.DetachPciDevice",
  476. user="root", input="00:%s" % vmdev)
  477. subprocess.check_call(
  478. ['sudo', 'xl', 'pci-detach', str(self.xid), pci])
  479. except subprocess.CalledProcessError as e:
  480. self.log.exception('Failed to detach PCI device {!r} on the fly,'
  481. ' changes will be seen after VM restart.'.format(pci), e)
  482. #
  483. # methods for changing domain state
  484. #
  485. def start(self, preparing_dvm=False, start_guid=True,
  486. notify_function=None, mem_required=None):
  487. '''Start domain
  488. :param bool preparing_dvm: FIXME
  489. :param bool start_guid: FIXME
  490. :param collections.Callable notify_function: FIXME
  491. :param int mem_required: FIXME
  492. '''
  493. # Intentionally not used is_running(): eliminate also "Paused",
  494. # "Crashed", "Halting"
  495. if self.get_power_state() != 'Halted':
  496. raise qubes.exc.QubesVMNotHaltedError(self)
  497. self.log.info('Starting {}'.format(self.name))
  498. self.fire_event_pre('domain-pre-start', preparing_dvm=preparing_dvm,
  499. start_guid=start_guid, mem_required=mem_required)
  500. self.verify_files()
  501. if self.netvm is not None:
  502. if self.netvm.qid != 0:
  503. if not self.netvm.is_running():
  504. self.netvm.start(start_guid=start_guid,
  505. notify_function=notify_function)
  506. self.storage.prepare_for_vm_startup()
  507. self._update_libvirt_domain()
  508. qmemman_client = self.request_memory(mem_required)
  509. # Bind pci devices to pciback driver
  510. for pci in self.devices['pci']:
  511. try:
  512. node = self.app.vmm.libvirt_conn.nodeDeviceLookupByName(
  513. 'pci_0000_' + pci.replace(':', '_').replace('.', '_'))
  514. except libvirt.libvirtError as e:
  515. if e.get_error_code() == libvirt.VIR_ERR_NO_NODE_DEVICE:
  516. raise qubes.exc.QubesException(
  517. 'PCI device {!r} does not exist (domain {!r})'.format(
  518. pci, self.name))
  519. try:
  520. node.dettach()
  521. except libvirt.libvirtError as e:
  522. if e.get_error_code() == libvirt.VIR_ERR_INTERNAL_ERROR:
  523. # allreaddy dettached
  524. pass
  525. else:
  526. raise
  527. self.libvirt_domain.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED)
  528. try:
  529. self.fire_event('domain-spawn',
  530. preparing_dvm=preparing_dvm, start_guid=start_guid)
  531. self.log.info('Setting Qubes DB info for the VM')
  532. self.start_qubesdb()
  533. self.create_qdb_entries()
  534. if preparing_dvm:
  535. self.qdb.write('/dvm', '1')
  536. self.log.warning('Activating the {} VM'.format(self.name))
  537. self.libvirt_domain.resume()
  538. # close() is not really needed, because the descriptor is
  539. # close-on-exec anyway, the reason to postpone close() is that
  540. # possibly xl is not done constructing the domain after its main
  541. # process exits so we close() when we know the domain is up the
  542. # successful unpause is some indicator of it
  543. if qmemman_client:
  544. qmemman_client.close()
  545. # if self._start_guid_first and start_guid and not preparing_dvm \
  546. # and os.path.exists('/var/run/shm.id'):
  547. # self.start_guid()
  548. if not preparing_dvm:
  549. self.start_qrexec_daemon()
  550. self.fire_event('domain-start',
  551. preparing_dvm=preparing_dvm, start_guid=start_guid)
  552. except: # pylint: disable=bare-except
  553. if self.is_running() or self.is_paused():
  554. # This avoids losing the exception if an exception is raised in
  555. # self.force_shutdown(), because the vm is not running or paused
  556. self.force_shutdown()
  557. raise
  558. def shutdown(self, force=False):
  559. '''Shutdown domain.
  560. :raises qubes.exc.QubesVMNotStartedError: \
  561. when domain is already shut down.
  562. '''
  563. if not self.is_running(): # TODO not self.is_halted()
  564. raise qubes.exc.QubesVMNotStartedError(self)
  565. self.fire_event_pre('domain-pre-shutdown', force=force)
  566. # try to gracefully detach PCI devices before shutdown, to mitigate
  567. # timeouts on forcible detach at domain destroy; if that fails, too bad
  568. for pci in self.devices['pci']:
  569. try:
  570. self.libvirt_domain.detachDevice(self.lvxml_pci_dev(pci))
  571. except libvirt.libvirtError as e:
  572. self.log.warning(
  573. 'error while gracefully detaching PCI device ({!r}) during'
  574. ' shutdown of {!r}; error code: {!r}; continuing'
  575. ' anyway'.format(pci, self.name, e.get_error_code()),
  576. exc_info=1)
  577. self.libvirt_domain.shutdown()
  578. def kill(self):
  579. '''Forcefuly shutdown (destroy) domain.
  580. :raises qubes.exc.QubesVMNotStartedError: \
  581. when domain is already shut down.
  582. '''
  583. if not self.is_running() and not self.is_paused():
  584. raise qubes.exc.QubesVMNotStartedError(self)
  585. self.libvirt_domain.destroy()
  586. def force_shutdown(self, *args, **kwargs):
  587. '''Deprecated alias for :py:meth:`kill`'''
  588. warnings.warn(
  589. 'Call to deprecated function force_shutdown(), use kill() instead',
  590. DeprecationWarning, stacklevel=2)
  591. self.kill(*args, **kwargs)
  592. def suspend(self):
  593. '''Suspend (pause) domain.
  594. :raises qubes.exc.QubesVMNotRunnignError: \
  595. when domain is already shut down.
  596. :raises qubes.exc.QubesNotImplemetedError: \
  597. when domain has PCI devices attached.
  598. '''
  599. if not self.is_running() and not self.is_paused():
  600. raise qubes.exc.QubesVMNotRunningError(self)
  601. if len(self.devices['pci']) > 0:
  602. raise qubes.exc.QubesNotImplementedError(
  603. 'Cannot suspend domain {!r} which has PCI devices attached' \
  604. .format(self.name))
  605. else:
  606. if self.hvm:
  607. self.libvirt_domain.pause()
  608. else:
  609. self.libvirt_domain.suspend()
  610. def pause(self):
  611. '''Pause (suspend) domain. This currently delegates to \
  612. :py:meth:`suspend`.'''
  613. if not self.is_running():
  614. raise qubes.exc.QubesVMNotRunningError(self)
  615. self.suspend()
  616. def resume(self):
  617. '''Resume suspended domain.
  618. :raises qubes.exc.QubesVMNotSuspendedError: when machine is not paused
  619. :raises qubes.exc.QubesVMError: when machine is suspended
  620. '''
  621. if self.get_power_state() == "Suspended":
  622. raise qubes.exc.QubesVMError(self,
  623. 'Cannot resume suspended domain {!r}'.format(self.name))
  624. else:
  625. self.unpause()
  626. def unpause(self):
  627. '''Resume (unpause) a domain'''
  628. if not self.is_paused():
  629. raise qubes.exc.QubesVMNotPausedError(self)
  630. self.libvirt_domain.resume()
  631. def run(self, command, user=None, autostart=False, notify_function=None,
  632. passio=False, passio_popen=False, passio_stderr=False,
  633. ignore_stderr=False, localcmd=None, wait=False, gui=True,
  634. filter_esc=False):
  635. '''Run specified command inside domain
  636. :param str command: the command to be run
  637. :param str user: user to run the command as
  638. :param bool autostart: if :py:obj:`True`, machine will be started if \
  639. it is not running
  640. :param collections.Callable notify_function: FIXME, may go away
  641. :param bool passio: FIXME
  642. :param bool passio_popen: if :py:obj:`True`, \
  643. :py:class:`subprocess.Popen` object has connected ``stdin`` and \
  644. ``stdout``
  645. :param bool passio_stderr: if :py:obj:`True`, \
  646. :py:class:`subprocess.Popen` has additionaly ``stderr`` connected
  647. :param bool ignore_stderr: if :py:obj:`True`, ``stderr`` is connected \
  648. to :file:`/dev/null`
  649. :param str localcmd: local command to communicate with remote command
  650. :param bool wait: if :py:obj:`True`, wait for command completion
  651. :param bool gui: when autostarting, also start gui daemon
  652. :param bool filter_esc: filter escape sequences to protect terminal \
  653. emulator
  654. '''
  655. if user is None:
  656. user = self.default_user
  657. null = None
  658. if not self.is_running() and not self.is_paused():
  659. if not autostart:
  660. raise qubes.exc.QubesVMNotRunningError(self)
  661. if notify_function is not None:
  662. notify_function('info',
  663. 'Starting the {!r} VM...'.format(self.name))
  664. self.start(start_guid=gui, notify_function=notify_function)
  665. if self.is_paused():
  666. # XXX what about autostart?
  667. raise qubes.exc.QubesVMNotRunningError(
  668. self, 'Domain {!r} is paused'.format(self.name))
  669. if not self.is_qrexec_running():
  670. raise qubes.exc.QubesVMError(
  671. self, 'Domain {!r}: qrexec not connected'.format(self.name))
  672. self.fire_event_pre('domain-cmd-pre-run', start_guid=gui)
  673. args = [qubes.config.system_path['qrexec_client_path'],
  674. '-d', str(self.name),
  675. '{}:{}'.format(user, command)]
  676. if localcmd is not None:
  677. args += ['-l', localcmd]
  678. if filter_esc:
  679. args += ['-t']
  680. if os.isatty(sys.stderr.fileno()):
  681. args += ['-T']
  682. call_kwargs = {}
  683. if ignore_stderr or not passio:
  684. null = open("/dev/null", "r+")
  685. call_kwargs['stderr'] = null
  686. if not passio:
  687. call_kwargs['stdin'] = null
  688. call_kwargs['stdout'] = null
  689. if passio_popen:
  690. popen_kwargs = {'stdout': subprocess.PIPE}
  691. popen_kwargs['stdin'] = subprocess.PIPE
  692. if passio_stderr:
  693. popen_kwargs['stderr'] = subprocess.PIPE
  694. else:
  695. popen_kwargs['stderr'] = call_kwargs.get('stderr', None)
  696. p = subprocess.Popen(args, **popen_kwargs)
  697. if null:
  698. null.close()
  699. return p
  700. if not wait and not passio:
  701. args += ["-e"]
  702. retcode = subprocess.call(args, **call_kwargs)
  703. if null:
  704. null.close()
  705. return retcode
  706. def run_service(self, service, source=None, user=None,
  707. passio_popen=False, input=None, localcmd=None, gui=False,
  708. wait=True, passio_stderr=False):
  709. '''Run service on this VM
  710. **passio_popen** and **input** are mutually exclusive.
  711. :param str service: service name
  712. :param qubes.vm.qubesvm.QubesVM: source domain as presented to this VM
  713. :param str user: username to run service as
  714. :param bool passio_popen: passed verbatim to :py:meth:`run`
  715. :param str input: string passed as input to service
  716. ''' # pylint: disable=redefined-builtin
  717. if len([i for i in (input, passio_popen, localcmd) if i]) > 1:
  718. raise TypeError(
  719. 'input, passio_popen and localcmd cannot be used together')
  720. if not wait and (localcmd or input):
  721. raise ValueError("Cannot use wait=False with input or "
  722. "localcmd specified")
  723. if passio_stderr and not passio_popen:
  724. raise TypeError('passio_stderr can be used only with passio_popen')
  725. if input:
  726. # Internally use passio_popen, but do not return POpen object to
  727. # the user - use internally for p.communicate()
  728. passio_popen = True
  729. source = 'dom0' if source is None else self.app.domains[source].name
  730. p = self.run('QUBESRPC {} {}'.format(service, source),
  731. localcmd=localcmd, passio_popen=passio_popen, user=user, wait=wait,
  732. gui=gui, passio_stderr=passio_stderr)
  733. if input:
  734. p.communicate(input)
  735. return p.returncode
  736. else:
  737. return p
  738. def request_memory(self, mem_required=None):
  739. # overhead of per-qube/per-vcpu Xen structures,
  740. # taken from OpenStack nova/virt/xenapi/driver.py
  741. # see https://wiki.openstack.org/wiki/XenServer/Overhead
  742. # add an extra MB because Nova rounds up to MBs
  743. if not qmemman_present:
  744. return
  745. MEM_OVERHEAD_BASE = (3 + 1) * 1024 * 1024
  746. MEM_OVERHEAD_PER_VCPU = 3 * 1024 * 1024 / 2
  747. if mem_required is None:
  748. mem_required = int(self.memory) * 1024 * 1024
  749. qmemman_client = qubes.qmemman.client.QMemmanClient()
  750. try:
  751. mem_required_with_overhead = mem_required + MEM_OVERHEAD_BASE \
  752. + self.vcpus * MEM_OVERHEAD_PER_VCPU
  753. got_memory = qmemman_client.request_memory(
  754. mem_required_with_overhead)
  755. except IOError as e:
  756. raise IOError('Failed to connect to qmemman: {!s}'.format(e))
  757. if not got_memory:
  758. qmemman_client.close()
  759. raise qubes.exc.QubesMemoryError(self)
  760. return qmemman_client
  761. def start_qrexec_daemon(self):
  762. '''Start qrexec daemon.
  763. :raises OSError: when starting fails.
  764. '''
  765. self.log.debug('Starting the qrexec daemon')
  766. qrexec_args = [str(self.xid), self.name, self.default_user]
  767. if not self.debug:
  768. qrexec_args.insert(0, "-q")
  769. qrexec_env = os.environ.copy()
  770. if not self.features.check_with_template('qrexec', not self.hvm):
  771. self.log.debug(
  772. 'Starting the qrexec daemon in background, because of features')
  773. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  774. else:
  775. qrexec_env['QREXEC_STARTUP_TIMEOUT'] = str(self.qrexec_timeout)
  776. try:
  777. subprocess.check_call(
  778. [qubes.config.system_path["qrexec_daemon_path"]] + qrexec_args,
  779. env=qrexec_env)
  780. except subprocess.CalledProcessError:
  781. raise qubes.exc.QubesVMError(self, 'Cannot execute qrexec-daemon!')
  782. def start_qubesdb(self):
  783. '''Start QubesDB daemon.
  784. :raises OSError: when starting fails.
  785. '''
  786. self.log.info('Starting Qubes DB')
  787. # FIXME #1694 #1241
  788. retcode = subprocess.call([
  789. qubes.config.system_path["qubesdb_daemon_path"],
  790. str(self.xid),
  791. self.name])
  792. if retcode != 0:
  793. raise qubes.exc.QubesException('Cannot execute qubesdb-daemon')
  794. def wait_for_session(self):
  795. '''Wait until machine finished boot sequence.
  796. This is done by executing qubes RPC call that checks if dummy system
  797. service (which is started late in standard runlevel) is active.
  798. '''
  799. self.log.info('Waiting for qubes-session')
  800. # Note : User root is redefined to SYSTEM in the Windows agent code
  801. p = self.run('QUBESRPC qubes.WaitForSession none',
  802. user="root", passio_popen=True, gui=False, wait=True)
  803. p.communicate(input=self.default_user)
  804. # TODO move to storage
  805. def create_on_disk(self, source_template=None):
  806. '''Create files needed for VM.
  807. :param qubes.vm.templatevm.TemplateVM source_template: Template to use
  808. (if :py:obj:`None`, use domain's own template
  809. '''
  810. if source_template is None and hasattr(self, 'template'):
  811. # pylint: disable=no-member
  812. source_template = self.template
  813. self.storage.create_on_disk(source_template)
  814. self.log.info('Creating icon symlink: {} -> {}'.format(
  815. self.icon_path, self.label.icon_path))
  816. if hasattr(os, "symlink"):
  817. os.symlink(self.label.icon_path, self.icon_path)
  818. else:
  819. shutil.copy(self.label.icon_path, self.icon_path)
  820. # fire hooks
  821. self.fire_event('domain-create-on-disk', source_template)
  822. # TODO move to storage
  823. def resize_private_img(self, size):
  824. '''Resize private image.'''
  825. if size >= self.get_private_img_sz():
  826. raise qubes.exc.QubesValueError('Cannot shrink private.img')
  827. # resize the image
  828. self.storage.resize_private_img(size)
  829. # and then the filesystem
  830. # FIXME move this to qubes.storage.xen.XenVMStorage
  831. retcode = 0
  832. if self.is_running():
  833. retcode = self.run('''
  834. while [ "`blockdev --getsize64 /dev/xvdb`" -lt {0} ]; do
  835. head /dev/xvdb >/dev/null;
  836. sleep 0.2;
  837. done;
  838. resize2fs /dev/xvdb'''.format(size), user="root", wait=True)
  839. if retcode != 0:
  840. raise qubes.exc.QubesException('resize2fs failed')
  841. # TODO move to storage
  842. def resize_root_img(self, size, allow_start=False):
  843. if hasattr(self, 'template'):
  844. raise qubes.exc.QubesVMError(self,
  845. 'Cannot resize root.img of template based qube. Resize the'
  846. ' root.img of the template instead.')
  847. # TODO self.is_halted
  848. if self.is_running():
  849. raise qubes.exc.QubesVMNotHaltedError(self,
  850. 'Cannot resize root.img of a running qube')
  851. if size < self.get_root_img_sz():
  852. raise qubes.exc.QubesValueError(
  853. 'For your own safety, shrinking of root.img is disabled. If you'
  854. ' really know what you are doing, use `truncate` manually.')
  855. with open(self.root_img, 'a+b') as fd:
  856. fd.truncate(size)
  857. if False: #self.hvm:
  858. return
  859. if not allow_start:
  860. raise qubes.exc.QubesException(
  861. 'The qube has to be started to complete the operation, but is'
  862. ' required not to start. Either run the operation again'
  863. ' allowing starting of the qube this time, or run resize2fs'
  864. ' in the qube manually.')
  865. self.start(start_guid=False)
  866. # TODO run_service #1695
  867. self.run('resize2fs /dev/mapper/dmroot', user='root',
  868. wait=True, gui=False)
  869. self.shutdown()
  870. while self.is_running(): #1696
  871. time.sleep(1)
  872. def remove_from_disk(self):
  873. '''Remove domain remnants from disk.'''
  874. self.fire_event('domain-remove-from-disk')
  875. self.storage.remove_from_disk()
  876. def clone_disk_files(self, src):
  877. '''Clone files from other vm.
  878. :param qubes.vm.qubesvm.QubesVM src: source VM
  879. '''
  880. if src.is_running(): # XXX what about paused?
  881. raise qubes.exc.QubesVMNotHaltedError(
  882. self, 'Cannot clone a running domain {!r}'.format(self.name))
  883. self.storage.clone_disk_files(src)
  884. if src.icon_path is not None \
  885. and os.path.exists(src.dir_path) \
  886. and self.icon_path is not None:
  887. if os.path.islink(src.icon_path):
  888. icon_path = os.readlink(src.icon_path)
  889. self.log.info(
  890. 'Creating icon symlink {} -> {}'.format(
  891. self.icon_path, icon_path))
  892. os.symlink(icon_path, self.icon_path)
  893. else:
  894. self.log.info(
  895. 'Copying icon {} -> {}'.format(
  896. src.icon_path, self.icon_path))
  897. shutil.copy(src.icon_path, self.icon_path)
  898. # fire hooks
  899. self.fire_event('domain-clone-files', src)
  900. #
  901. # methods for querying domain state
  902. #
  903. # state of the machine
  904. def get_power_state(self):
  905. '''Return power state description string.
  906. Return value may be one of those:
  907. =============== ========================================================
  908. return value meaning
  909. =============== ========================================================
  910. ``'Halted'`` Machine is not active.
  911. ``'Transient'`` Machine is running, but does not have :program:`guid`
  912. or :program:`qrexec` available.
  913. ``'Running'`` Machine is ready and running.
  914. ``'Paused'`` Machine is paused (currently not available, see below).
  915. ``'Suspended'`` Machine is S3-suspended.
  916. ``'Halting'`` Machine is in process of shutting down.
  917. ``'Dying'`` Machine crashed and is unusable.
  918. ``'Crashed'`` Machine crashed and is unusable, probably because of
  919. bug in dom0.
  920. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  921. is undefined).
  922. =============== ========================================================
  923. ``Paused`` state is currently unavailable because of missing code in
  924. libvirt/xen glue.
  925. FIXME: graph below may be incomplete and wrong. Click on method name to
  926. see its documentation.
  927. .. graphviz::
  928. digraph {
  929. node [fontname="sans-serif"];
  930. edge [fontname="mono"];
  931. Halted;
  932. NA;
  933. Dying;
  934. Crashed;
  935. Transient;
  936. Halting;
  937. Running;
  938. Paused [color=gray75 fontcolor=gray75];
  939. Suspended;
  940. NA -> Halted;
  941. Halted -> NA [constraint=false];
  942. Halted -> Transient
  943. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  944. Transient -> Running;
  945. Running -> Halting
  946. [xlabel="shutdown()"
  947. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  948. constraint=false];
  949. Halting -> Dying -> Halted [constraint=false];
  950. /* cosmetic, invisible edges to put rank constraint */
  951. Dying -> Halting [style="invis"];
  952. Halting -> Transient [style="invis"];
  953. Running -> Halted
  954. [label="force_shutdown()"
  955. URL="#qubes.vm.qubesvm.QubesVM.force_shutdown"
  956. constraint=false];
  957. Running -> Crashed [constraint=false];
  958. Crashed -> Halted [constraint=false];
  959. Running -> Paused
  960. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  961. color=gray75 fontcolor=gray75];
  962. Running -> Suspended
  963. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  964. color=gray50 fontcolor=gray50];
  965. Paused -> Running
  966. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  967. color=gray75 fontcolor=gray75];
  968. Suspended -> Running
  969. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  970. color=gray50 fontcolor=gray50];
  971. Running -> Suspended
  972. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  973. Suspended -> Running
  974. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  975. { rank=source; Halted NA };
  976. { rank=same; Transient Halting };
  977. { rank=same; Crashed Dying };
  978. { rank=sink; Paused Suspended };
  979. }
  980. .. seealso::
  981. http://wiki.libvirt.org/page/VM_lifecycle
  982. Description of VM life cycle from the point of view of libvirt.
  983. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  984. Libvirt's enum describing precise state of a domain.
  985. ''' # pylint: disable=too-many-return-statements
  986. libvirt_domain = self.libvirt_domain
  987. if libvirt_domain is None:
  988. return 'Halted'
  989. try:
  990. if libvirt_domain.isActive():
  991. # pylint: disable=line-too-long
  992. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  993. return "Paused"
  994. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  995. return "Crashed"
  996. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  997. return "Halting"
  998. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  999. return "Dying"
  1000. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED:
  1001. return "Suspended"
  1002. else:
  1003. if not self.is_fully_usable():
  1004. return "Transient"
  1005. else:
  1006. return "Running"
  1007. else:
  1008. return 'Halted'
  1009. except libvirt.libvirtError as e:
  1010. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1011. return 'Halted'
  1012. else:
  1013. raise
  1014. assert False
  1015. def is_running(self):
  1016. '''Check whether this domain is running.
  1017. :returns: :py:obj:`True` if this domain is started, \
  1018. :py:obj:`False` otherwise.
  1019. :rtype: bool
  1020. '''
  1021. # TODO context manager #1693
  1022. return self.libvirt_domain and self.libvirt_domain.isActive()
  1023. def is_paused(self):
  1024. '''Check whether this domain is paused.
  1025. :returns: :py:obj:`True` if this domain is paused, \
  1026. :py:obj:`False` otherwise.
  1027. :rtype: bool
  1028. '''
  1029. return self.libvirt_domain \
  1030. and self.libvirt_domain.state() == libvirt.VIR_DOMAIN_PAUSED
  1031. def is_qrexec_running(self):
  1032. '''Check whether qrexec for this domain is available.
  1033. :returns: :py:obj:`True` if qrexec is running, \
  1034. :py:obj:`False` otherwise.
  1035. :rtype: bool
  1036. '''
  1037. if self.xid < 0:
  1038. return False
  1039. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1040. def is_fully_usable(self):
  1041. return all(self.fire_event('domain-is-fully-usable'))
  1042. @qubes.events.handler('domain-is-fully-usable')
  1043. def on_domain_is_fully_usable(self, event):
  1044. '''Check whether domain is running and sane.
  1045. Currently this checks for running qrexec.
  1046. '''
  1047. # Running gui-daemon implies also VM running
  1048. if not self.is_qrexec_running():
  1049. yield False
  1050. # memory and disk
  1051. def get_mem(self):
  1052. '''Get current memory usage from VM.
  1053. :returns: Memory usage [FIXME unit].
  1054. :rtype: FIXME
  1055. '''
  1056. if self.libvirt_domain is None:
  1057. return 0
  1058. try:
  1059. if not self.libvirt_domain.isActive():
  1060. return 0
  1061. return self.libvirt_domain.info()[1]
  1062. except libvirt.libvirtError as e:
  1063. if e.get_error_code() in (
  1064. # qube no longer exists
  1065. libvirt.VIR_ERR_NO_DOMAIN,
  1066. # libxl_domain_info failed (race condition from isActive)
  1067. libvirt.VIR_ERR_INTERNAL_ERROR,
  1068. ):
  1069. return 0
  1070. else:
  1071. self.log.exception(
  1072. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1073. raise
  1074. def get_mem_static_max(self):
  1075. '''Get maximum memory available to VM.
  1076. :returns: Memory limit [FIXME unit].
  1077. :rtype: FIXME
  1078. '''
  1079. if self.libvirt_domain is None:
  1080. return 0
  1081. try:
  1082. return self.libvirt_domain.maxMemory()
  1083. except libvirt.libvirtError as e:
  1084. if e.get_error_code() in (
  1085. # qube no longer exists
  1086. libvirt.VIR_ERR_NO_DOMAIN,
  1087. # libxl_domain_info failed (race condition from isActive)
  1088. libvirt.VIR_ERR_INTERNAL_ERROR,
  1089. ):
  1090. return 0
  1091. else:
  1092. self.log.exception(
  1093. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1094. raise
  1095. def get_cputime(self):
  1096. '''Get total CPU time burned by this domain since start.
  1097. :returns: CPU time usage [FIXME unit].
  1098. :rtype: FIXME
  1099. '''
  1100. if self.libvirt_domain is None:
  1101. return 0
  1102. if self.libvirt_domain is None:
  1103. return 0
  1104. if not self.libvirt_domain.isActive():
  1105. return 0
  1106. try:
  1107. if not self.libvirt_domain.isActive():
  1108. return 0
  1109. # this does not work, because libvirt
  1110. # return self.libvirt_domain.getCPUStats(
  1111. # libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1112. return self.libvirt_domain.info()[4]
  1113. except libvirt.libvirtError as e:
  1114. if e.get_error_code() in (
  1115. # qube no longer exists
  1116. libvirt.VIR_ERR_NO_DOMAIN,
  1117. # libxl_domain_info failed (race condition from isActive)
  1118. libvirt.VIR_ERR_INTERNAL_ERROR,
  1119. ):
  1120. return 0
  1121. else:
  1122. self.log.exception(
  1123. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1124. raise
  1125. # XXX shouldn't this go only to vms that have root image?
  1126. def get_disk_utilization_root_img(self):
  1127. '''Get space that is actually ocuppied by :py:attr:`root_img`.
  1128. Root image is a sparse file, so it is probably much less than logical
  1129. available space.
  1130. :returns: domain's real disk image size [FIXME unit]
  1131. :rtype: FIXME
  1132. .. seealso:: :py:meth:`get_root_img_sz`
  1133. '''
  1134. return qubes.storage.get_disk_usage(self.root_img)
  1135. # XXX shouldn't this go only to vms that have root image?
  1136. def get_root_img_sz(self):
  1137. '''Get image size of :py:attr:`root_img`.
  1138. Root image is a sparse file, so it is probably much more than ocuppied
  1139. physical space.
  1140. :returns: domain's virtual disk size [FIXME unit]
  1141. :rtype: FIXME
  1142. .. seealso:: :py:meth:`get_disk_utilization_root_img`
  1143. '''
  1144. if not os.path.exists(self.root_img):
  1145. return 0
  1146. return os.path.getsize(self.root_img)
  1147. def get_disk_utilization_private_img(self):
  1148. '''Get space that is actually ocuppied by :py:attr:`private_img`.
  1149. Private image is a sparse file, so it is probably much less than
  1150. logical available space.
  1151. :returns: domain's real disk image size [FIXME unit]
  1152. :rtype: FIXME
  1153. .. seealso:: :py:meth:`get_private_img_sz`
  1154. ''' # pylint: disable=invalid-name
  1155. return qubes.storage.get_disk_usage(self.private_img)
  1156. def get_private_img_sz(self):
  1157. '''Get image size of :py:attr:`private_img`.
  1158. Private image is a sparse file, so it is probably much more than
  1159. ocuppied physical space.
  1160. :returns: domain's virtual disk size [FIXME unit]
  1161. :rtype: FIXME
  1162. .. seealso:: :py:meth:`get_disk_utilization_private_img`
  1163. '''
  1164. return self.storage.get_private_img_sz()
  1165. def get_disk_utilization(self):
  1166. '''Return total space actually occuppied by all files belonging to \
  1167. this domain.
  1168. :returns: domain's total disk usage [FIXME unit]
  1169. :rtype: FIXME
  1170. '''
  1171. return qubes.storage.get_disk_usage(self.dir_path)
  1172. # TODO move to storage
  1173. def verify_files(self):
  1174. '''Verify that files accessed by this machine are sane.
  1175. On success, returns normally. On failure, raises exception.
  1176. '''
  1177. self.storage.verify_files()
  1178. if not os.path.exists(
  1179. os.path.join(self.storage.kernels_dir, 'vmlinuz')):
  1180. raise qubes.exc.QubesException(
  1181. 'VM kernel does not exist: {0}'.format(
  1182. os.path.join(self.storage.kernels_dir, 'vmlinuz')))
  1183. if not os.path.exists(
  1184. os.path.join(self.storage.kernels_dir, 'initramfs')):
  1185. raise qubes.exc.QubesException(
  1186. 'VM initramfs does not exist: {0}'.format(
  1187. os.path.join(self.storage.kernels_dir, 'initramfs')))
  1188. self.fire_event('domain-verify-files')
  1189. return True
  1190. # miscellanous
  1191. def get_start_time(self):
  1192. '''Tell when machine was started.
  1193. :rtype: datetime.datetime
  1194. '''
  1195. if not self.is_running():
  1196. return None
  1197. # TODO shouldn't this be qubesdb?
  1198. start_time = self.app.vmm.xs.read('',
  1199. '/vm/{}/start_time'.format(self.uuid))
  1200. if start_time != '':
  1201. return datetime.datetime.fromtimestamp(float(start_time))
  1202. else:
  1203. return None
  1204. # XXX this probably should go to AppVM
  1205. def is_outdated(self):
  1206. '''Check whether domain needs restart to update root image from \
  1207. template.
  1208. :returns: :py:obj:`True` if is outdated, :py:obj:`False` otherwise.
  1209. :rtype: bool
  1210. '''
  1211. # pylint: disable=no-member
  1212. # Makes sense only on VM based on template
  1213. if self.template is None:
  1214. return False
  1215. if not self.is_running():
  1216. return False
  1217. if not hasattr(self.template, 'rootcow_img'):
  1218. return False
  1219. rootimg_inode = os.stat(self.template.root_img)
  1220. try:
  1221. rootcow_inode = os.stat(self.template.rootcow_img)
  1222. except OSError:
  1223. # The only case when rootcow_img doesn't exists is in the middle of
  1224. # commit_changes, so VM is outdated right now
  1225. return True
  1226. current_dmdev = "/dev/mapper/snapshot-{0:x}:{1}-{2:x}:{3}".format(
  1227. rootimg_inode[2], rootimg_inode[1],
  1228. rootcow_inode[2], rootcow_inode[1])
  1229. # FIXME
  1230. # 51712 (0xCA00) is xvda
  1231. # backend node name not available through xenapi :(
  1232. used_dmdev = self.app.vmm.xs.read('',
  1233. '/local/domain/0/backend/vbd/{}/51712/node'.format(self.xid))
  1234. return used_dmdev != current_dmdev
  1235. #
  1236. # helper methods
  1237. #
  1238. def relative_path(self, path):
  1239. '''Return path relative to py:attr:`dir_path`.
  1240. :param str path: Path in question.
  1241. :returns: Relative path.
  1242. '''
  1243. return os.path.relpath(path, self.dir_path)
  1244. def create_qdb_entries(self):
  1245. '''Create entries in Qubes DB.
  1246. '''
  1247. # pylint: disable=no-member
  1248. self.qdb.write('/name', self.name)
  1249. self.qdb.write('/type', self.__class__.__name__)
  1250. self.qdb.write('/updateable', str(self.updateable))
  1251. self.qdb.write('/persistence', 'full' if self.updateable else 'rw-only')
  1252. self.qdb.write('/debug', str(int(self.debug)))
  1253. try:
  1254. self.qdb.write('/template', self.template.name)
  1255. except AttributeError:
  1256. self.qdb.write('/template', '')
  1257. self.qdb.write('/random-seed',
  1258. base64.b64encode(qubes.utils.urandom(64)))
  1259. if self.provides_network:
  1260. self.qdb.write('/network-provider/gateway', self.gateway)
  1261. self.qdb.write('/network-provider/netmask', self.netmask)
  1262. for i, addr in zip(itertools.count(start=1), self.dns):
  1263. self.qdb.write('/network-provider/dns-{}'.format(i), addr)
  1264. if self.netvm is not None:
  1265. self.qdb.write('/network/ip', self.ip)
  1266. self.qdb.write('/network/netmask', self.netvm.netmask)
  1267. self.qdb.write('/network/gateway', self.netvm.gateway)
  1268. for i, addr in zip(itertools.count(start=1), self.dns):
  1269. self.qdb.write('/network/dns-{}'.format(i), addr)
  1270. tzname = qubes.utils.get_timezone()
  1271. if tzname:
  1272. self.qdb.write('/timezone', tzname)
  1273. for feature, value in self.features.items():
  1274. self.qdb.write('/features/{0}'.format(feature),
  1275. str(value) if value else '')
  1276. self.qdb.write('/devices/block', '')
  1277. self.qdb.write('/devices/usb', '')
  1278. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1279. # xenstore for it until decided otherwise
  1280. if qmemman_present:
  1281. self.app.vmm.xs.set_permissions('',
  1282. '/local/domain/{}/memory'.format(self.xid),
  1283. [{'dom': self.xid}])
  1284. self.fire_event('domain-qdb-create')
  1285. def _update_libvirt_domain(self):
  1286. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1287. domain_config = self.create_config_file()
  1288. try:
  1289. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1290. domain_config)
  1291. except libvirt.libvirtError as e:
  1292. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1293. and e.get_str2() == 'hvm':
  1294. raise qubes.exc.QubesVMError(self,
  1295. 'HVM qubes are not supported on this machine. '
  1296. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1297. else:
  1298. raise
  1299. #
  1300. # workshop -- those are to be reworked later
  1301. #
  1302. def get_prefmem(self):
  1303. # TODO: qmemman is still xen specific
  1304. untrusted_meminfo_key = self.app.vmm.xs.read('',
  1305. '/local/domain/{}/memory/meminfo'.format(self.xid))
  1306. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1307. return 0
  1308. domain = qubes.qmemman.DomainState(self.xid)
  1309. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1310. domain, untrusted_meminfo_key)
  1311. domain.memory_maximum = self.get_mem_static_max() * 1024
  1312. return qubes.qmemman.algo.prefmem(domain) / 1024
  1313. #
  1314. # landfill -- those are unneeded
  1315. #
  1316. # attrs = {
  1317. # XXX probably will be obsoleted by .events_enabled
  1318. # "_do_not_reset_firewall": { "func": lambda x: False },
  1319. # "_start_guid_first": { "func": lambda x: False },
  1320. # }
  1321. # this function appears unused
  1322. # def _cleanup_zombie_domains(self):
  1323. # """
  1324. # This function is workaround broken libxl (which leaves not fully
  1325. # created domain on failure) and vchan on domain crash behaviour
  1326. # @return: None
  1327. # """
  1328. # xc = self.get_xc_dominfo()
  1329. # if xc and xc['dying'] == 1:
  1330. # # GUID still running?
  1331. # guid_pidfile = '/var/run/qubes/guid-running.%d' % xc['domid']
  1332. # if os.path.exists(guid_pidfile):
  1333. # guid_pid = open(guid_pidfile).read().strip()
  1334. # os.kill(int(guid_pid), 15)
  1335. # # qrexec still running?
  1336. # if self.is_qrexec_running():
  1337. # #TODO: kill qrexec daemon
  1338. # pass