qubesvm.py 57 KB

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