qubesvm.py 58 KB

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