qubesvm.py 58 KB

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