qubesvm.py 58 KB

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