qubesvm.py 52 KB

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