qubesvm.py 59 KB

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