qubesvm.py 57 KB

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