qubesvm.py 59 KB

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