qubesvm.py 58 KB

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