qubesvm.py 58 KB

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