qubesvm.py 58 KB

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