qubesvm.py 58 KB

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