qubesvm.py 59 KB

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