qubesvm.py 57 KB

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