__init__.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  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) 2011-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. '''
  26. Qubes OS
  27. :copyright: © 2010-2015 Invisible Things Lab
  28. '''
  29. from __future__ import absolute_import
  30. __author__ = 'Invisible Things Lab'
  31. __license__ = 'GPLv2 or later'
  32. __version__ = 'R3'
  33. import ast
  34. import atexit
  35. import collections
  36. import errno
  37. import grp
  38. import logging
  39. import os
  40. import os.path
  41. import sys
  42. import tempfile
  43. import time
  44. import warnings
  45. import __builtin__
  46. import docutils.core
  47. import docutils.io
  48. import jinja2
  49. import lxml.etree
  50. import pkg_resources
  51. import qubes.config
  52. import qubes.events
  53. import qubes.exc
  54. import qubes.ext
  55. if os.name == 'posix':
  56. import fcntl
  57. elif os.name == 'nt':
  58. # pylint: disable=import-error
  59. import win32con
  60. import win32file
  61. import pywintypes
  62. else:
  63. raise RuntimeError("Qubes works only on POSIX or WinNT systems")
  64. import libvirt
  65. try:
  66. import xen.lowlevel.xs
  67. import xen.lowlevel.xc
  68. except ImportError:
  69. pass
  70. class VMMConnection(object):
  71. '''Connection to Virtual Machine Manager (libvirt)'''
  72. def __init__(self):
  73. self._libvirt_conn = None
  74. self._xs = None
  75. self._xc = None
  76. self._offline_mode = False
  77. @__builtin__.property
  78. def offline_mode(self):
  79. '''Check or enable offline mode (do not actually connect to vmm)'''
  80. return self._offline_mode
  81. @offline_mode.setter
  82. def offline_mode(self, value):
  83. if value and self._libvirt_conn is not None:
  84. raise qubes.exc.QubesException(
  85. 'Cannot change offline mode while already connected')
  86. self._offline_mode = value
  87. def _libvirt_error_handler(self, ctx, error):
  88. pass
  89. def init_vmm_connection(self):
  90. '''Initialise connection
  91. This method is automatically called when getting'''
  92. if self._libvirt_conn is not None:
  93. # Already initialized
  94. return
  95. if self._offline_mode:
  96. # Do not initialize in offline mode
  97. raise qubes.exc.QubesException(
  98. 'VMM operations disabled in offline mode')
  99. if 'xen.lowlevel.xs' in sys.modules:
  100. self._xs = xen.lowlevel.xs.xs()
  101. if 'xen.lowlevel.cs' in sys.modules:
  102. self._xc = xen.lowlevel.xc.xc()
  103. self._libvirt_conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  104. if self._libvirt_conn is None:
  105. raise qubes.exc.QubesException('Failed connect to libvirt driver')
  106. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  107. @__builtin__.property
  108. def libvirt_conn(self):
  109. '''Connection to libvirt'''
  110. self.init_vmm_connection()
  111. return self._libvirt_conn
  112. @__builtin__.property
  113. def xs(self):
  114. '''Connection to Xen Store
  115. This property in available only when running on Xen.
  116. '''
  117. # XXX what about the case when we run under KVM,
  118. # but xen modules are importable?
  119. if 'xen.lowlevel.xs' not in sys.modules:
  120. raise AttributeError(
  121. 'xs object is available under Xen hypervisor only')
  122. self.init_vmm_connection()
  123. return self._xs
  124. @__builtin__.property
  125. def xc(self):
  126. '''Connection to Xen
  127. This property in available only when running on Xen.
  128. '''
  129. # XXX what about the case when we run under KVM,
  130. # but xen modules are importable?
  131. if 'xen.lowlevel.xc' not in sys.modules:
  132. raise AttributeError(
  133. 'xc object is available under Xen hypervisor only')
  134. self.init_vmm_connection()
  135. return self._xs
  136. def __del__(self):
  137. if self._libvirt_conn:
  138. self._libvirt_conn.close()
  139. class QubesHost(object):
  140. '''Basic information about host machine
  141. :param qubes.Qubes app: Qubes application context (must have \
  142. :py:attr:`Qubes.vmm` attribute defined)
  143. '''
  144. def __init__(self, app):
  145. self.app = app
  146. self._no_cpus = None
  147. self._total_mem = None
  148. self._physinfo = None
  149. def _fetch(self):
  150. if self._no_cpus is not None:
  151. return
  152. # pylint: disable=unused-variable
  153. (model, memory, cpus, mhz, nodes, socket, cores, threads) = \
  154. self.app.vmm.libvirt_conn.getInfo()
  155. self._total_mem = long(memory) * 1024
  156. self._no_cpus = cpus
  157. self.app.log.debug('QubesHost: no_cpus={} memory_total={}'.format(
  158. self.no_cpus, self.memory_total))
  159. try:
  160. self.app.log.debug('QubesHost: xen_free_memory={}'.format(
  161. self.get_free_xen_memory()))
  162. except NotImplementedError:
  163. pass
  164. @__builtin__.property
  165. def memory_total(self):
  166. '''Total memory, in kbytes'''
  167. self._fetch()
  168. return self._total_mem
  169. @__builtin__.property
  170. def no_cpus(self):
  171. '''Number of CPUs'''
  172. self._fetch()
  173. return self._no_cpus
  174. def get_free_xen_memory(self):
  175. '''Get free memory from Xen's physinfo.
  176. :raises NotImplementedError: when not under Xen
  177. '''
  178. try:
  179. self._physinfo = self.app.xc.physinfo()
  180. except AttributeError:
  181. raise NotImplementedError('This function requires Xen hypervisor')
  182. return long(self._physinfo['free_memory'])
  183. def measure_cpu_usage(self, previous_time=None, previous=None,
  184. wait_time=1):
  185. '''Measure cpu usage for all domains at once.
  186. This function requires Xen hypervisor.
  187. .. versionchanged:: 3.0
  188. argument order to match return tuple
  189. :raises NotImplementedError: when not under Xen
  190. '''
  191. if previous is None:
  192. previous_time = time.time()
  193. previous = {}
  194. try:
  195. info = self.app.vmm.xc.domain_getinfo(0, qubes.config.max_qid)
  196. except AttributeError:
  197. raise NotImplementedError(
  198. 'This function requires Xen hypervisor')
  199. for vm in info:
  200. previous[vm['domid']] = {}
  201. previous[vm['domid']]['cpu_time'] = (
  202. vm['cpu_time'] / vm['online_vcpus'])
  203. previous[vm['domid']]['cpu_usage'] = 0
  204. time.sleep(wait_time)
  205. current_time = time.time()
  206. current = {}
  207. try:
  208. info = self.app.vmm.xc.domain_getinfo(0, qubes.config.max_qid)
  209. except AttributeError:
  210. raise NotImplementedError(
  211. 'This function requires Xen hypervisor')
  212. for vm in info:
  213. current[vm['domid']] = {}
  214. current[vm['domid']]['cpu_time'] = (
  215. vm['cpu_time'] / max(vm['online_vcpus'], 1))
  216. if vm['domid'] in previous.keys():
  217. current[vm['domid']]['cpu_usage'] = (
  218. float(current[vm['domid']]['cpu_time'] -
  219. previous[vm['domid']]['cpu_time']) /
  220. long(1000 ** 3) / (current_time - previous_time) * 100)
  221. if current[vm['domid']]['cpu_usage'] < 0:
  222. # VM has been rebooted
  223. current[vm['domid']]['cpu_usage'] = 0
  224. else:
  225. current[vm['domid']]['cpu_usage'] = 0
  226. return (current_time, current)
  227. class Label(object):
  228. '''Label definition for virtual machines
  229. Label specifies colour of the padlock displayed next to VM's name.
  230. When this is a :py:class:`qubes.vm.dispvm.DispVM`, padlock is overlayed
  231. with recycling pictogram.
  232. :param int index: numeric identificator of label
  233. :param str color: colour specification as in HTML (``#abcdef``)
  234. :param str name: label's name like "red" or "green"
  235. '''
  236. def __init__(self, index, color, name):
  237. #: numeric identificator of label
  238. self.index = index
  239. #: colour specification as in HTML (``#abcdef``)
  240. self.color = color
  241. #: label's name like "red" or "green"
  242. self.name = name
  243. #: freedesktop icon name, suitable for use in
  244. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme`
  245. self.icon = 'appvm-' + name
  246. #: freedesktop icon name, suitable for use in
  247. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme` on DispVMs
  248. self.icon_dispvm = 'dispvm-' + name
  249. @classmethod
  250. def fromxml(cls, xml):
  251. '''Create label definition from XML node
  252. :param lxml.etree._Element xml: XML node reference
  253. :rtype: :py:class:`qubes.Label`
  254. '''
  255. index = int(xml.get('id').split('-', 1)[1])
  256. color = xml.get('color')
  257. name = xml.text
  258. return cls(index, color, name)
  259. def __xml__(self):
  260. element = lxml.etree.Element(
  261. 'label', id='label-{}'.format(self.index), color=self.color)
  262. element.text = self.name
  263. return element
  264. def __str__(self):
  265. return self.name
  266. def __repr__(self):
  267. return '{}({!r}, {!r}, {!r})'.format(
  268. self.__class__.__name__,
  269. self.index,
  270. self.color,
  271. self.name)
  272. @__builtin__.property
  273. def icon_path(self):
  274. '''Icon path
  275. .. deprecated:: 2.0
  276. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  277. '''
  278. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  279. self.icon) + ".png"
  280. @__builtin__.property
  281. def icon_path_dispvm(self):
  282. '''Icon path
  283. .. deprecated:: 2.0
  284. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  285. '''
  286. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  287. self.icon_dispvm) + ".png"
  288. class VMCollection(object):
  289. '''A collection of Qubes VMs
  290. VMCollection supports ``in`` operator. You may test for ``qid``, ``name``
  291. and whole VM object's presence.
  292. Iterating over VMCollection will yield machine objects.
  293. '''
  294. def __init__(self, app):
  295. self.app = app
  296. self._dict = dict()
  297. def __repr__(self):
  298. return '<{} {!r}>'.format(
  299. self.__class__.__name__, list(sorted(self.keys())))
  300. def items(self):
  301. '''Iterate over ``(qid, vm)`` pairs'''
  302. for qid in self.qids():
  303. yield (qid, self[qid])
  304. def qids(self):
  305. '''Iterate over all qids
  306. qids are sorted by numerical order.
  307. '''
  308. return iter(sorted(self._dict.keys()))
  309. keys = qids
  310. def names(self):
  311. '''Iterate over all names
  312. names are sorted by lexical order.
  313. '''
  314. return iter(sorted(vm.name for vm in self._dict.values()))
  315. def vms(self):
  316. '''Iterate over all machines
  317. vms are sorted by qid.
  318. '''
  319. return iter(sorted(self._dict.values()))
  320. __iter__ = vms
  321. values = vms
  322. def add(self, value):
  323. '''Add VM to collection
  324. :param qubes.vm.BaseVM value: VM to add
  325. :raises TypeError: when value is of wrong type
  326. :raises ValueError: when there is already VM which has equal ``qid``
  327. '''
  328. # this violates duck typing, but is needed
  329. # for VMProperty to function correctly
  330. if not isinstance(value, qubes.vm.BaseVM):
  331. raise TypeError('{} holds only BaseVM instances'.format(
  332. self.__class__.__name__))
  333. if value.qid in self:
  334. raise ValueError('This collection already holds VM that has '
  335. 'qid={!r} ({!r})'.format(value.qid, self[value.qid]))
  336. if value.name in self:
  337. raise ValueError('This collection already holds VM that has '
  338. 'name={!r} ({!r})'.format(value.name, self[value.name]))
  339. self._dict[value.qid] = value
  340. value.events_enabled = True
  341. self.app.fire_event('domain-add', value)
  342. return value
  343. def __getitem__(self, key):
  344. if isinstance(key, int):
  345. return self._dict[key]
  346. if isinstance(key, basestring):
  347. for vm in self:
  348. if vm.name == key:
  349. return vm
  350. raise KeyError(key)
  351. if isinstance(key, qubes.vm.BaseVM):
  352. if key in self:
  353. return key
  354. raise KeyError(key)
  355. raise KeyError(key)
  356. def __delitem__(self, key):
  357. vm = self[key]
  358. self.app.fire_event_pre('domain-pre-delete', vm)
  359. del self._dict[vm.qid]
  360. self.app.fire_event('domain-delete', vm)
  361. def __contains__(self, key):
  362. return any((key == vm or key == vm.qid or key == vm.name)
  363. for vm in self)
  364. def __len__(self):
  365. return len(self._dict)
  366. def get_vms_based_on(self, template):
  367. template = self[template]
  368. return set(vm for vm in self
  369. if hasattr(vm, 'template') and vm.template == template)
  370. def get_vms_connected_to(self, netvm):
  371. new_vms = set([self[netvm]])
  372. dependent_vms = set()
  373. # Dependency resolving only makes sense on NetVM (or derivative)
  374. # if not self[netvm_qid].is_netvm():
  375. # return set([])
  376. while len(new_vms) > 0:
  377. cur_vm = new_vms.pop()
  378. for vm in cur_vm.connected_vms.values():
  379. if vm in dependent_vms:
  380. continue
  381. dependent_vms.add(vm.qid)
  382. # if vm.is_netvm():
  383. new_vms.add(vm.qid)
  384. return dependent_vms
  385. # XXX with Qubes Admin Api this will probably lead to race condition
  386. # whole process of creating and adding should be synchronised
  387. def get_new_unused_qid(self):
  388. used_ids = set(self.qids())
  389. for i in range(1, qubes.config.max_qid):
  390. if i not in used_ids:
  391. return i
  392. raise LookupError("Cannot find unused qid!")
  393. def get_new_unused_netid(self):
  394. used_ids = set([vm.netid for vm in self]) # if vm.is_netvm()])
  395. for i in range(1, qubes.config.max_netid):
  396. if i not in used_ids:
  397. return i
  398. raise LookupError("Cannot find unused netid!")
  399. class property(object): # pylint: disable=redefined-builtin,invalid-name
  400. '''Qubes property.
  401. This class holds one property that can be saved to and loaded from
  402. :file:`qubes.xml`. It is used for both global and per-VM properties.
  403. Property can be unset by ordinary ``del`` statement or assigning
  404. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  405. assignment/load) attempting to read a property will get its default value
  406. or, when no default, py:class:`exceptions.AttributeError`.
  407. :param str name: name of the property
  408. :param collections.Callable setter: if not :py:obj:`None`, this is used to \
  409. initialise value; first parameter to the function is holder instance \
  410. and the second is value; this is called before ``type``
  411. :param collections.Callable saver: function to coerce value to something \
  412. readable by setter
  413. :param type type: if not :py:obj:`None`, value is coerced to this type
  414. :param object default: default value; if callable, will be called with \
  415. holder as first argument
  416. :param int load_stage: stage when property should be loaded (see \
  417. :py:class:`Qubes` for description of stages)
  418. :param int order: order of evaluation (bigger order values are later)
  419. :param bool clone: :py:meth:`PropertyHolder.clone_properties` will not \
  420. include this property by default if :py:obj:`False`
  421. :param str ls_head: column head for :program:`qvm-ls`
  422. :param int ls_width: column width in :program:`qvm-ls`
  423. :param str doc: docstring; this should be one paragraph of plain RST, no \
  424. sphinx-specific features
  425. Setters and savers have following signatures:
  426. .. :py:function:: setter(self, prop, value)
  427. :noindex:
  428. :param self: instance of object that is holding property
  429. :param prop: property object
  430. :param value: value being assigned
  431. .. :py:function:: saver(self, prop, value)
  432. :noindex:
  433. :param self: instance of object that is holding property
  434. :param prop: property object
  435. :param value: value being saved
  436. :rtype: str
  437. :raises property.DontSave: when property should not be saved at all
  438. '''
  439. #: Assigning this value to property means setting it to its default value.
  440. #: If property has no default value, this will unset it.
  441. DEFAULT = object()
  442. # internal use only
  443. _NO_DEFAULT = object()
  444. def __init__(self, name, setter=None, saver=None, type=None,
  445. default=_NO_DEFAULT, write_once=False, load_stage=2, order=0,
  446. save_via_ref=False, clone=True,
  447. ls_head=None, ls_width=None, doc=None):
  448. # pylint: disable=redefined-builtin
  449. self.__name__ = name
  450. self._setter = setter
  451. self._saver = saver if saver is not None else (
  452. lambda self, prop, value: str(value))
  453. self._type = type
  454. self._default = default
  455. self._write_once = write_once
  456. self.order = order
  457. self.load_stage = load_stage
  458. self.save_via_ref = save_via_ref
  459. self.clone = clone
  460. self.__doc__ = doc
  461. self._attr_name = '_qubesprop_' + name
  462. if ls_head is not None or ls_width is not None:
  463. self.ls_head = ls_head or self.__name__.replace('_', '-').upper()
  464. self.ls_width = max(ls_width or 0, len(self.ls_head) + 1)
  465. def __get__(self, instance, owner):
  466. if instance is None:
  467. return self
  468. # XXX this violates duck typing, shall we keep it?
  469. if not isinstance(instance, PropertyHolder):
  470. raise AttributeError('qubes.property should be used on '
  471. 'qubes.PropertyHolder instances only')
  472. try:
  473. return getattr(instance, self._attr_name)
  474. except AttributeError:
  475. if self._default is self._NO_DEFAULT:
  476. raise AttributeError(
  477. 'property {!r} not set'.format(self.__name__))
  478. elif isinstance(self._default, collections.Callable):
  479. return self._default(instance)
  480. else:
  481. return self._default
  482. def __set__(self, instance, value):
  483. self._enforce_write_once(instance)
  484. if value is self.__class__.DEFAULT:
  485. self.__delete__(instance)
  486. return
  487. try:
  488. oldvalue = getattr(instance, self.__name__)
  489. has_oldvalue = True
  490. except AttributeError:
  491. has_oldvalue = False
  492. if self._setter is not None:
  493. value = self._setter(instance, self, value)
  494. if self._type not in (None, type(value)):
  495. value = self._type(value)
  496. if has_oldvalue:
  497. instance.fire_event_pre('property-pre-set:' + self.__name__,
  498. self.__name__, value, oldvalue)
  499. else:
  500. instance.fire_event_pre('property-pre-set:' + self.__name__,
  501. self.__name__, value)
  502. instance._property_init(self, value) # pylint: disable=protected-access
  503. if has_oldvalue:
  504. instance.fire_event('property-set:' + self.__name__, self.__name__,
  505. value, oldvalue)
  506. else:
  507. instance.fire_event('property-set:' + self.__name__, self.__name__,
  508. value)
  509. def __delete__(self, instance):
  510. self._enforce_write_once(instance)
  511. try:
  512. oldvalue = getattr(instance, self.__name__)
  513. has_oldvalue = True
  514. except AttributeError:
  515. has_oldvalue = False
  516. if has_oldvalue:
  517. instance.fire_event_pre('property-pre-del:' + self.__name__,
  518. self.__name__, oldvalue)
  519. else:
  520. instance.fire_event_pre('property-pre-del:' + self.__name__,
  521. self.__name__)
  522. delattr(instance, self._attr_name)
  523. if has_oldvalue:
  524. instance.fire_event('property-del:' + self.__name__,
  525. self.__name__, oldvalue)
  526. else:
  527. instance.fire_event('property-del:' + self.__name__,
  528. self.__name__)
  529. def __repr__(self):
  530. default = ' default={!r}'.format(self._default) \
  531. if self._default is not self._NO_DEFAULT \
  532. else ''
  533. return '<{} object at {:#x} name={!r}{}>'.format(
  534. self.__class__.__name__, id(self), self.__name__, default) \
  535. def __hash__(self):
  536. return hash(self.__name__)
  537. def __eq__(self, other):
  538. return isinstance(other, property) and self.__name__ == other.__name__
  539. def _enforce_write_once(self, instance):
  540. if self._write_once and not instance.property_is_default(self):
  541. raise AttributeError(
  542. 'property {!r} is write-once and already set'.format(
  543. self.__name__))
  544. #
  545. # exceptions
  546. #
  547. class DontSave(Exception):
  548. '''This exception may be raised from saver to sign that property should
  549. not be saved.
  550. '''
  551. pass
  552. @staticmethod
  553. def dontsave(self, prop, value):
  554. '''Dummy saver that never saves anything.'''
  555. # pylint: disable=bad-staticmethod-argument,unused-argument
  556. raise property.DontSave()
  557. #
  558. # some setters provided
  559. #
  560. @staticmethod
  561. def forbidden(self, prop, value):
  562. '''Property setter that forbids loading a property.
  563. This is used to effectively disable property in classes which inherit
  564. unwanted property. When someone attempts to load such a property, it
  565. :throws AttributeError: always
  566. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  567. raise AttributeError(
  568. 'setting {} property on {} instance is forbidden'.format(
  569. prop.__name__, self.__class__.__name__))
  570. @staticmethod
  571. def bool(self, prop, value):
  572. '''Property setter for boolean properties.
  573. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  574. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  575. :py:obj:`True`.
  576. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  577. if isinstance(value, basestring):
  578. lcvalue = value.lower()
  579. if lcvalue in ('0', 'no', 'false', 'off'):
  580. return False
  581. if lcvalue in ('1', 'yes', 'true', 'on'):
  582. return True
  583. raise ValueError(
  584. 'Invalid literal for boolean property: {!r}'.format(value))
  585. return bool(value)
  586. class PropertyHolder(qubes.events.Emitter):
  587. '''Abstract class for holding :py:class:`qubes.property`
  588. Events fired by instances of this class:
  589. .. event:: property-load (subject, event)
  590. Fired once after all properties are loaded from XML. Individual
  591. ``property-set`` events are not fired.
  592. .. event:: property-set:<propname> \
  593. (subject, event, name, newvalue[, oldvalue])
  594. Fired when property changes state. Signature is variable,
  595. *oldvalue* is present only if there was an old value.
  596. :param name: Property name
  597. :param newvalue: New value of the property
  598. :param oldvalue: Old value of the property
  599. .. event:: property-pre-set:<propname> \
  600. (subject, event, name, newvalue[, oldvalue])
  601. Fired before property changes state. Signature is variable,
  602. *oldvalue* is present only if there was an old value.
  603. :param name: Property name
  604. :param newvalue: New value of the property
  605. :param oldvalue: Old value of the property
  606. .. event:: property-del:<propname> \
  607. (subject, event, name[, oldvalue])
  608. Fired when property gets deleted (is set to default). Signature is
  609. variable, *oldvalue* is present only if there was an old value.
  610. :param name: Property name
  611. :param oldvalue: Old value of the property
  612. .. event:: property-pre-del:<propname> \
  613. (subject, event, name[, oldvalue])
  614. Fired before property gets deleted (is set to default). Signature
  615. is variable, *oldvalue* is present only if there was an old value.
  616. :param name: Property name
  617. :param oldvalue: Old value of the property
  618. Members:
  619. '''
  620. def __init__(self, xml, **kwargs):
  621. self.xml = xml
  622. propvalues = {}
  623. all_names = set(prop.__name__ for prop in self.property_list())
  624. for key in list(kwargs.keys()):
  625. if not key in all_names:
  626. continue
  627. propvalues[key] = kwargs.pop(key)
  628. super(PropertyHolder, self).__init__(**kwargs)
  629. for key, value in propvalues.items():
  630. setattr(self, key, value)
  631. @classmethod
  632. def property_list(cls, load_stage=None):
  633. '''List all properties attached to this VM's class
  634. :param load_stage: Filter by load stage
  635. :type load_stage: :py:func:`int` or :py:obj:`None`
  636. '''
  637. props = set()
  638. for class_ in cls.__mro__:
  639. props.update(prop for prop in class_.__dict__.values()
  640. if isinstance(prop, property))
  641. if load_stage is not None:
  642. props = set(prop for prop in props
  643. if prop.load_stage == load_stage)
  644. return sorted(props,
  645. key=lambda prop: (prop.load_stage, prop.order, prop.__name__))
  646. def _property_init(self, prop, value):
  647. '''Initialise property to a given value, without side effects.
  648. :param qubes.property prop: property object of particular interest
  649. :param value: value
  650. '''
  651. # pylint: disable=protected-access
  652. setattr(self, self.property_get_def(prop)._attr_name, value)
  653. def property_is_default(self, prop):
  654. '''Check whether property is in it's default value.
  655. Properties when unset may return some default value, so
  656. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  657. method allows for checking if the value returned is in fact it's
  658. default value.
  659. :param qubes.property prop: property object of particular interest
  660. :rtype: bool
  661. ''' # pylint: disable=protected-access
  662. # both property_get_def() and ._attr_name may throw AttributeError,
  663. # which we don't want to catch
  664. attrname = self.property_get_def(prop)._attr_name
  665. return not hasattr(self, attrname)
  666. @classmethod
  667. def property_get_def(cls, prop):
  668. '''Return property definition object.
  669. If prop is already :py:class:`qubes.property` instance, return the same
  670. object.
  671. :param prop: property object or name
  672. :type prop: qubes.property or str
  673. :rtype: qubes.property
  674. '''
  675. if isinstance(prop, qubes.property):
  676. return prop
  677. for p in cls.property_list():
  678. if p.__name__ == prop:
  679. return p
  680. raise AttributeError('No property {!r} found in {!r}'.format(
  681. prop, cls))
  682. def load_properties(self, load_stage=None):
  683. '''Load properties from immediate children of XML node.
  684. ``property-set`` events are not fired for each individual property.
  685. :param int load_stage: Stage of loading.
  686. '''
  687. if self.xml is None:
  688. return
  689. all_names = set(
  690. prop.__name__ for prop in self.property_list(load_stage))
  691. for node in self.xml.xpath('./properties/property'):
  692. name = node.get('name')
  693. value = node.get('ref') or node.text
  694. if not name in all_names:
  695. continue
  696. setattr(self, name, value)
  697. def xml_properties(self, with_defaults=False):
  698. '''Iterator that yields XML nodes representing set properties.
  699. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  700. properties which were not set explicite, but have default values \
  701. filled.
  702. '''
  703. properties = lxml.etree.Element('properties')
  704. for prop in self.property_list():
  705. # pylint: disable=protected-access
  706. try:
  707. value = getattr(
  708. self, (prop.__name__ if with_defaults else prop._attr_name))
  709. except AttributeError:
  710. continue
  711. try:
  712. value = prop._saver(self, prop, value)
  713. except property.DontSave:
  714. continue
  715. element = lxml.etree.Element('property', name=prop.__name__)
  716. if prop.save_via_ref:
  717. element.set('ref', value)
  718. else:
  719. element.text = value
  720. properties.append(element)
  721. return properties
  722. # this was clone_attrs
  723. def clone_properties(self, src, proplist=None):
  724. '''Clone properties from other object.
  725. :param PropertyHolder src: source object
  726. :param list proplist: list of properties \
  727. (:py:obj:`None` or omit for all properties except those with \
  728. :py:attr:`property.clone` set to :py:obj:`False`)
  729. '''
  730. if proplist is None:
  731. proplist = [prop for prop in self.property_list()
  732. if prop.clone]
  733. else:
  734. proplist = [prop for prop in self.property_list()
  735. if prop.__name__ in proplist or prop in proplist]
  736. for prop in proplist:
  737. try:
  738. # pylint: disable=protected-access
  739. self._property_init(prop, getattr(src, prop._attr_name))
  740. except AttributeError:
  741. continue
  742. self.fire_event('clone-properties', src, proplist)
  743. def property_require(self, prop, allow_none=False, hard=False):
  744. '''Complain badly when property is not set.
  745. :param prop: property name or object
  746. :type prop: qubes.property or str
  747. :param bool allow_none: if :py:obj:`True`, don't complain if \
  748. :py:obj:`None` is found
  749. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  750. if :py:obj:`False`, log warning instead
  751. '''
  752. if isinstance(prop, qubes.property):
  753. prop = prop.__name__
  754. try:
  755. value = getattr(self, prop)
  756. if value is None and not allow_none:
  757. raise AttributeError()
  758. except AttributeError:
  759. # pylint: disable=no-member
  760. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  761. if hard:
  762. raise AssertionError(msg)
  763. else:
  764. # pylint: disable=no-member
  765. self.log.fatal(msg)
  766. import qubes.vm
  767. class VMProperty(property):
  768. '''Property that is referring to a VM
  769. :param type vmclass: class that returned VM is supposed to be instance of
  770. and all supported by :py:class:`property` with the exception of ``type`` \
  771. and ``setter``
  772. '''
  773. _none_value = ''
  774. def __init__(self, name, vmclass=qubes.vm.BaseVM, allow_none=False,
  775. **kwargs):
  776. if 'type' in kwargs:
  777. raise TypeError(
  778. "'type' keyword parameter is unsupported in {}".format(
  779. self.__class__.__name__))
  780. if 'setter' in kwargs:
  781. raise TypeError(
  782. "'setter' keyword parameter is unsupported in {}".format(
  783. self.__class__.__name__))
  784. if not issubclass(vmclass, qubes.vm.BaseVM):
  785. raise TypeError(
  786. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  787. super(VMProperty, self).__init__(name,
  788. saver=(lambda self_, prop, value:
  789. self._none_value if value is None else value.name),
  790. **kwargs)
  791. self.vmclass = vmclass
  792. self.allow_none = allow_none
  793. def __set__(self, instance, value):
  794. if value == self._none_value:
  795. value = None
  796. if value is None:
  797. if self.allow_none:
  798. super(VMProperty, self).__set__(instance, value)
  799. return
  800. else:
  801. raise ValueError(
  802. 'Property {!r} does not allow setting to {!r}'.format(
  803. self.__name__, value))
  804. app = instance if isinstance(instance, Qubes) else instance.app
  805. try:
  806. vm = app.domains[value]
  807. except KeyError:
  808. raise qubes.exc.QubesVMNotFoundError(value)
  809. if not isinstance(vm, self.vmclass):
  810. raise TypeError('wrong VM class: domains[{!r}] if of type {!s} '
  811. 'and not {!s}'.format(value,
  812. vm.__class__.__name__,
  813. self.vmclass.__name__))
  814. super(VMProperty, self).__set__(instance, vm)
  815. import qubes.vm.qubesvm
  816. import qubes.vm.templatevm
  817. class Qubes(PropertyHolder):
  818. '''Main Qubes application
  819. :param str store: path to ``qubes.xml``
  820. The store is loaded in stages:
  821. 1. In the first stage there are loaded some basic features from store
  822. (currently labels).
  823. 2. In the second stage stubs for all VMs are loaded. They are filled
  824. with their basic properties, like ``qid`` and ``name``.
  825. 3. In the third stage all global properties are loaded. They often
  826. reference VMs, like default netvm, so they should be filled after
  827. loading VMs.
  828. 4. In the fourth stage all remaining VM properties are loaded. They
  829. also need all VMs loaded, because they represent dependencies
  830. between VMs like aforementioned netvm.
  831. 5. In the fifth stage there are some fixups to ensure sane system
  832. operation.
  833. This class emits following events:
  834. .. event:: domain-added (subject, event, vm)
  835. When domain is added.
  836. :param subject: Event emitter
  837. :param event: Event name (``'domain-added'``)
  838. :param vm: Domain object
  839. .. event:: domain-deleted (subject, event, vm)
  840. When domain is deleted. VM still has reference to ``app`` object,
  841. but is not contained within VMCollection.
  842. :param subject: Event emitter
  843. :param event: Event name (``'domain-deleted'``)
  844. :param vm: Domain object
  845. Methods and attributes:
  846. '''
  847. default_netvm = VMProperty('default_netvm', load_stage=3,
  848. default=None, allow_none=True,
  849. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  850. that AppVMs are not connected to the Internet.''')
  851. default_fw_netvm = VMProperty('default_fw_netvm', load_stage=3,
  852. default=None, allow_none=True,
  853. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  854. that ProxyVMs (including FirewallVM) are not connected to the
  855. Internet.''')
  856. default_template = VMProperty('default_template', load_stage=3,
  857. vmclass=qubes.vm.templatevm.TemplateVM,
  858. doc='Default template for new AppVMs')
  859. updatevm = VMProperty('updatevm', load_stage=3,
  860. allow_none=True,
  861. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  862. TemplateVMs''')
  863. clockvm = VMProperty('clockvm', load_stage=3,
  864. allow_none=True,
  865. doc='Which VM to use as NTP proxy for updating AdminVM')
  866. default_kernel = property('default_kernel', load_stage=3,
  867. doc='Which kernel to use when not overriden in VM')
  868. # TODO #1637 #892
  869. check_updates_vm = property('check_updates_vm',
  870. type=bool, setter=property.bool,
  871. default=True,
  872. doc='check for updates inside qubes')
  873. def __init__(self, store=None, load=True, **kwargs):
  874. #: logger instance for logging global messages
  875. self.log = logging.getLogger('app')
  876. # pylint: disable=no-member
  877. self.extensions = set(ext.load()(self)
  878. for ext in pkg_resources.iter_entry_points('qubes.ext'))
  879. #: collection of all VMs managed by this Qubes instance
  880. self.domains = VMCollection(self)
  881. #: collection of all available labels for VMs
  882. self.labels = {}
  883. #: Connection to VMM
  884. self.vmm = VMMConnection()
  885. #: Information about host system
  886. self.host = QubesHost(self)
  887. if store is not None:
  888. self._store = store
  889. else:
  890. self._store = os.environ.get('QUBES_XML_PATH',
  891. os.path.join(
  892. qubes.config.system_path['qubes_base_dir'],
  893. qubes.config.system_path['qubes_store_filename']))
  894. super(Qubes, self).__init__(xml=None, **kwargs)
  895. self.__load_timestamp = None
  896. #: jinja2 environment for libvirt XML templates
  897. self.env = jinja2.Environment(
  898. loader=jinja2.FileSystemLoader('/usr/share/qubes/templates'),
  899. undefined=jinja2.StrictUndefined)
  900. if load:
  901. self.load()
  902. self.events_enabled = True
  903. def load(self):
  904. '''Open qubes.xml
  905. :throws EnvironmentError: failure on parsing store
  906. :throws xml.parsers.expat.ExpatError: failure on parsing store
  907. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  908. '''
  909. fd = os.open(self._store, os.O_RDWR) # no O_CREAT
  910. fh = os.fdopen(fd, 'rb')
  911. if os.name == 'posix':
  912. fcntl.lockf(fh, fcntl.LOCK_EX)
  913. elif os.name == 'nt':
  914. # pylint: disable=protected-access
  915. win32file.LockFileEx(
  916. win32file._get_osfhandle(fh.fileno()),
  917. win32con.LOCKFILE_EXCLUSIVE_LOCK,
  918. 0, -0x10000,
  919. pywintypes.OVERLAPPED())
  920. self.xml = lxml.etree.parse(fh)
  921. # stage 1: load labels
  922. for node in self.xml.xpath('./labels/label'):
  923. label = Label.fromxml(node)
  924. self.labels[label.index] = label
  925. # stage 2: load VMs
  926. for node in self.xml.xpath('./domains/domain'):
  927. # pylint: disable=no-member
  928. cls = self.get_vm_class(node.get('class'))
  929. vm = cls(self, node)
  930. vm.load_properties(load_stage=2)
  931. vm.init_log()
  932. self.domains.add(vm)
  933. if not 0 in self.domains:
  934. self.domains.add(qubes.vm.adminvm.AdminVM(
  935. self, None, qid=0, name='dom0'))
  936. # stage 3: load global properties
  937. self.load_properties(load_stage=3)
  938. # stage 4: fill all remaining VM properties
  939. for vm in self.domains:
  940. vm.load_properties(load_stage=4)
  941. # stage 5: misc fixups
  942. self.property_require('default_fw_netvm', allow_none=True)
  943. self.property_require('default_netvm', allow_none=True)
  944. self.property_require('default_template')
  945. self.property_require('clockvm', allow_none=True)
  946. self.property_require('updatevm', allow_none=True)
  947. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  948. # using 123/udp port)
  949. if hasattr(self, 'clockvm') and self.clockvm is not None:
  950. if self.clockvm.features.get('services/ntpd', False):
  951. self.log.warning("VM set as clockvm ({!r}) has enabled 'ntpd' "
  952. "service! Expect failure when syncing time in dom0.".format(
  953. self.clockvm))
  954. else:
  955. self.clockvm.features['services/ntpd'] = ''
  956. for vm in self.domains:
  957. vm.events_enabled = True
  958. vm.fire_event('domain-load')
  959. # get a file timestamp (before closing it - still holding the lock!),
  960. # to detect whether anyone else have modified it in the meantime
  961. self.__load_timestamp = os.path.getmtime(self._store)
  962. # intentionally do not call explicit unlock
  963. fh.close()
  964. del fh
  965. def __xml__(self):
  966. element = lxml.etree.Element('qubes')
  967. element.append(self.xml_labels())
  968. element.append(self.xml_properties())
  969. domains = lxml.etree.Element('domains')
  970. for vm in self.domains:
  971. domains.append(vm.__xml__())
  972. element.append(domains)
  973. return element
  974. def save(self):
  975. '''Save all data to qubes.xml
  976. There are several problems with saving :file:`qubes.xml` which must be
  977. mitigated:
  978. - Running out of disk space. No space left should not result in empty
  979. file. This is done by writing to temporary file and then renaming.
  980. - Attempts to write two or more files concurrently. This is done by
  981. sophisticated locking.
  982. :throws EnvironmentError: failure on saving
  983. '''
  984. while True:
  985. fd_old = os.open(self._store, os.O_RDWR | os.O_CREAT)
  986. if os.name == 'posix':
  987. fcntl.lockf(fd_old, fcntl.LOCK_EX)
  988. elif os.name == 'nt':
  989. # pylint: disable=protected-access
  990. overlapped = pywintypes.OVERLAPPED()
  991. win32file.LockFileEx(
  992. win32file._get_osfhandle(fd_old),
  993. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  994. # While we were waiting for lock, someone could have unlink()ed (or
  995. # rename()d) our file out of the filesystem. We have to ensure we
  996. # got lock on something linked to filesystem. If not, try again.
  997. if os.fstat(fd_old) == os.stat(self._store):
  998. break
  999. else:
  1000. os.close(fd_old)
  1001. if self.__load_timestamp:
  1002. current_file_timestamp = os.path.getmtime(self._store)
  1003. if current_file_timestamp != self.__load_timestamp:
  1004. os.close(fd_old)
  1005. raise qubes.exc.QubesException(
  1006. "Someone else modified qubes.xml in the meantime")
  1007. fh_new = tempfile.NamedTemporaryFile(prefix=self._store, delete=False)
  1008. lxml.etree.ElementTree(self.__xml__()).write(
  1009. fh_new, encoding='utf-8', pretty_print=True)
  1010. fh_new.flush()
  1011. os.chmod(fh_new.name, 0660)
  1012. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  1013. os.rename(fh_new.name, self._store)
  1014. # intentionally do not call explicit unlock to not unlock the file
  1015. # before all buffers are flushed
  1016. fh_new.close()
  1017. # update stored mtime, in case of multiple save() calls without
  1018. # loading qubes.xml again
  1019. self.__load_timestamp = os.path.getmtime(self._store)
  1020. os.close(fd_old)
  1021. @classmethod
  1022. def create_empty_store(cls, *args, **kwargs):
  1023. self = cls(*args, load=False, **kwargs)
  1024. self.labels = {
  1025. 1: Label(1, '0xcc0000', 'red'),
  1026. 2: Label(2, '0xf57900', 'orange'),
  1027. 3: Label(3, '0xedd400', 'yellow'),
  1028. 4: Label(4, '0x73d216', 'green'),
  1029. 5: Label(5, '0x555753', 'gray'),
  1030. 6: Label(6, '0x3465a4', 'blue'),
  1031. 7: Label(7, '0x75507b', 'purple'),
  1032. 8: Label(8, '0x000000', 'black'),
  1033. }
  1034. self.domains.add(
  1035. qubes.vm.adminvm.AdminVM(self, None, qid=0, name='dom0'))
  1036. self.save()
  1037. return self
  1038. def xml_labels(self):
  1039. '''Serialise labels
  1040. :rtype: lxml.etree._Element
  1041. '''
  1042. labels = lxml.etree.Element('labels')
  1043. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  1044. labels.append(label.__xml__())
  1045. return labels
  1046. def get_vm_class(self, clsname):
  1047. '''Find the class for a domain.
  1048. Classess are registered as setuptools' entry points in ``qubes.vm``
  1049. group. Any package may supply their own classess.
  1050. :param str clsname: name of the class
  1051. :return type: class
  1052. '''
  1053. epoints = tuple(pkg_resources.iter_entry_points('qubes.vm', clsname))
  1054. if not epoints:
  1055. raise qubes.exc.QubesException(
  1056. 'no such VM class: {!r}'.format(clsname))
  1057. elif len(epoints) > 1:
  1058. raise qubes.exc.QubesException(
  1059. 'more than 1 implementation of {!r} found: {}'.format(
  1060. clsname,
  1061. ', '.join(
  1062. '{}.{}'.format(ep.module_name, '.'.join(ep.attrs))
  1063. for ep in epoints)))
  1064. return epoints[0].load()
  1065. def add_new_vm(self, cls, qid=None, **kwargs):
  1066. '''Add new Virtual Machine to colletion
  1067. '''
  1068. if qid is None:
  1069. qid = self.domains.get_new_unused_qid()
  1070. # handle default template; specifically allow template=None (do not
  1071. # override it with default template)
  1072. if 'template' not in kwargs and hasattr(cls, 'template'):
  1073. kwargs['template'] = self.default_template
  1074. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  1075. def get_label(self, label):
  1076. '''Get label as identified by index or name
  1077. :throws KeyError: when label is not found
  1078. '''
  1079. # first search for index, verbatim
  1080. try:
  1081. return self.labels[label]
  1082. except KeyError:
  1083. pass
  1084. # then search for name
  1085. for i in self.labels.values():
  1086. if i.name == label:
  1087. return i
  1088. # last call, if label is a number represented as str, search in indices
  1089. try:
  1090. return self.labels[int(label)]
  1091. except (KeyError, ValueError):
  1092. pass
  1093. raise KeyError(label)
  1094. @qubes.events.handler('domain-pre-delete')
  1095. def on_domain_pre_deleted(self, event, vm):
  1096. # pylint: disable=unused-argument
  1097. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  1098. appvms = self.domains.get_vms_based_on(vm)
  1099. if appvms:
  1100. raise qubes.exc.QubesException(
  1101. 'Cannot remove template that has dependent AppVMs. '
  1102. 'Affected are: {}'.format(', '.join(
  1103. vm.name for name in sorted(appvms))))
  1104. @qubes.events.handler('domain-delete')
  1105. def on_domain_deleted(self, event, vm):
  1106. # pylint: disable=unused-argument
  1107. for propname in (
  1108. 'default_netvm',
  1109. 'default_fw_netvm',
  1110. 'clockvm',
  1111. 'updatevm',
  1112. 'default_template',
  1113. ):
  1114. try:
  1115. if getattr(self, propname) == vm:
  1116. delattr(self, propname)
  1117. except AttributeError:
  1118. pass
  1119. @qubes.events.handler('property-pre-set:clockvm')
  1120. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1121. # pylint: disable=unused-argument,no-self-use
  1122. if newvalue is None:
  1123. return
  1124. if newvalue.features.get('services/ntpd', False):
  1125. raise qubes.exc.QubesVMError(newvalue,
  1126. 'Cannot set {!r} as {!r} since it has ntpd enabled.'.format(
  1127. newvalue.name, name))
  1128. else:
  1129. newvalue.features['services/ntpd'] = ''
  1130. @qubes.events.handler(
  1131. 'property-pre-set:default_netvm',
  1132. 'property-pre-set:default_fw_netvm')
  1133. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1134. oldvalue=None):
  1135. # pylint: disable=unused-argument,invalid-name
  1136. if newvalue is not None and oldvalue is not None \
  1137. and oldvalue.is_running() and not newvalue.is_running() \
  1138. and self.domains.get_vms_connected_to(oldvalue):
  1139. raise qubes.exc.QubesVMNotRunningError(newvalue,
  1140. 'Cannot change {!r} to domain that '
  1141. 'is not running ({!r}).'.format(name, newvalue.name))
  1142. @qubes.events.handler('property-set:default_fw_netvm')
  1143. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1144. oldvalue=None):
  1145. # pylint: disable=unused-argument,invalid-name
  1146. for vm in self.domains:
  1147. if not vm.provides_network and vm.property_is_default('netvm'):
  1148. # fire property-del:netvm as it is responsible for resetting
  1149. # netvm to it's default value
  1150. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  1151. @qubes.events.handler('property-set:default_netvm')
  1152. def on_property_set_default_netvm(self, event, name, newvalue,
  1153. oldvalue=None):
  1154. # pylint: disable=unused-argument
  1155. for vm in self.domains:
  1156. if vm.provides_network and vm.property_is_default('netvm'):
  1157. # fire property-del:netvm as it is responsible for resetting
  1158. # netvm to it's default value
  1159. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)