qubesvm.py 61 KB

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