qubesvm.py 58 KB

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