__init__.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  1. #!/usr/bin/python2 -O
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. '''
  5. Qubes OS
  6. :copyright: © 2010-2014 Invisible Things Lab
  7. '''
  8. __author__ = 'Invisible Things Lab'
  9. __license__ = 'GPLv2 or later'
  10. __version__ = 'R3'
  11. import ast
  12. import atexit
  13. import collections
  14. import grp
  15. import os
  16. import os.path
  17. import sys
  18. import tempfile
  19. import time
  20. import warnings
  21. import __builtin__
  22. import docutils.core
  23. import docutils.io
  24. import lxml.etree
  25. import xml.parsers.expat
  26. import qubes.ext
  27. if os.name == 'posix':
  28. import fcntl
  29. elif os.name == 'nt':
  30. import win32con
  31. import win32file
  32. import pywintypes
  33. else:
  34. raise RuntimeError, "Qubes works only on POSIX or WinNT systems"
  35. import libvirt
  36. try:
  37. import xen.lowlevel.xs
  38. import xen.lowlevel.xc
  39. except ImportError:
  40. pass
  41. #: FIXME documentation
  42. MAX_QID = 253
  43. #: FIXME documentation
  44. MAX_NETID = 253
  45. class QubesException(Exception):
  46. '''Exception that can be shown to the user'''
  47. pass
  48. class VMMConnection(object):
  49. '''Connection to Virtual Machine Manager (libvirt)'''
  50. def __init__(self):
  51. self._libvirt_conn = None
  52. self._xs = None
  53. self._xc = None
  54. self._offline_mode = False
  55. @__builtin__.property
  56. def offline_mode(self):
  57. '''Check or enable offline mode (do not actually connect to vmm)'''
  58. return self._offline_mode
  59. @offline_mode.setter
  60. def offline_mode(self, value):
  61. if value and self._libvirt_conn is not None:
  62. raise QubesException("Cannot change offline mode while already connected")
  63. self._offline_mode = value
  64. def _libvirt_error_handler(self, ctx, error):
  65. pass
  66. def init_vmm_connection(self):
  67. '''Initialise connection
  68. This method is automatically called when getting'''
  69. if self._libvirt_conn is not None:
  70. # Already initialized
  71. return
  72. if self._offline_mode:
  73. # Do not initialize in offline mode
  74. raise QubesException("VMM operations disabled in offline mode")
  75. if 'xen.lowlevel.xs' in sys.modules:
  76. self._xs = xen.lowlevel.xs.xs()
  77. if 'xen.lowlevel.cs' in sys.modules:
  78. self._xc = xen.lowlevel.xc.xc()
  79. self._libvirt_conn = libvirt.open(defaults['libvirt_uri'])
  80. if self._libvirt_conn == None:
  81. raise QubesException("Failed connect to libvirt driver")
  82. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  83. atexit.register(self._libvirt_conn.close)
  84. @__builtin__.property
  85. def libvirt_conn(self):
  86. '''Connection to libvirt'''
  87. self.init_vmm_connection()
  88. return self._libvirt_conn
  89. @__builtin__.property
  90. def xs(self):
  91. '''Connection to Xen Store
  92. This property in available only when running on Xen.
  93. '''
  94. # XXX what about the case when we run under KVM, but xen modules are importable?
  95. if 'xen.lowlevel.xs' not in sys.modules:
  96. raise AttributeError('xs object is available under Xen hypervisor only')
  97. self.init_vmm_connection()
  98. return self._xs
  99. @__builtin__.property
  100. def xc(self):
  101. '''Connection to Xen
  102. This property in available only when running on Xen.
  103. '''
  104. # XXX what about the case when we run under KVM, but xen modules are importable?
  105. if 'xen.lowlevel.xc' not in sys.modules:
  106. raise AttributeError('xc object is available under Xen hypervisor only')
  107. self.init_vmm_connection()
  108. return self._xs
  109. class QubesHost(object):
  110. '''Basic information about host machine
  111. :param qubes.Qubes app: Qubes application context (must have :py:attr:`Qubes.vmm` attribute defined)
  112. '''
  113. def __init__(self, app):
  114. self._app = app
  115. self._no_cpus = None
  116. def _fetch(self):
  117. if self._no_cpus is not None:
  118. return
  119. (model, memory, cpus, mhz, nodes, socket, cores, threads) = \
  120. self._app.vmm.libvirt_conn.getInfo()
  121. self._total_mem = long(memory)*1024
  122. self._no_cpus = cpus
  123. self.app.log.debug('QubesHost: no_cpus={} memory_total={}'.format(self.no_cpus, self.memory_total))
  124. try:
  125. self.app.log.debug('QubesHost: xen_free_memory={}'.format(self.get_free_xen_memory()))
  126. except NotImplementedError:
  127. pass
  128. @__builtin__.property
  129. def memory_total(self):
  130. '''Total memory, in bytes'''
  131. self._fetch()
  132. return self._total_mem
  133. @__builtin__.property
  134. def no_cpus(self):
  135. '''Number of CPUs'''
  136. self._fetch()
  137. return self._no_cpus
  138. def get_free_xen_memory(self):
  139. '''Get free memory from Xen's physinfo.
  140. :raises NotImplementedError: when not under Xen
  141. '''
  142. try:
  143. self._physinfo = self.app.xc.physinfo()
  144. except AttributeError:
  145. raise NotImplementedError('This function requires Xen hypervisor')
  146. return long(self._physinfo['free_memory'])
  147. def measure_cpu_usage(self, previous_time=None, previous=None,
  148. wait_time=1):
  149. '''Measure cpu usage for all domains at once.
  150. This function requires Xen hypervisor.
  151. .. versionchanged:: 3.0
  152. argument order to match return tuple
  153. :raises NotImplementedError: when not under Xen
  154. '''
  155. if previous is None:
  156. previous_time = time.time()
  157. previous = {}
  158. try:
  159. info = self._app.vmm.xc.domain_getinfo(0, qubes_max_qid)
  160. except AttributeError:
  161. raise NotImplementedError(
  162. 'This function requires Xen hypervisor')
  163. for vm in info:
  164. previous[vm['domid']] = {}
  165. previous[vm['domid']]['cpu_time'] = (
  166. vm['cpu_time'] / vm['online_vcpus'])
  167. previous[vm['domid']]['cpu_usage'] = 0
  168. time.sleep(wait_time)
  169. current_time = time.time()
  170. current = {}
  171. try:
  172. info = self._app.vmm.xc.domain_getinfo(0, qubes_max_qid)
  173. except AttributeError:
  174. raise NotImplementedError(
  175. 'This function requires Xen hypervisor')
  176. for vm in info:
  177. current[vm['domid']] = {}
  178. current[vm['domid']]['cpu_time'] = (
  179. vm['cpu_time'] / max(vm['online_vcpus'], 1))
  180. if vm['domid'] in previous.keys():
  181. current[vm['domid']]['cpu_usage'] = (
  182. float(current[vm['domid']]['cpu_time'] -
  183. previous[vm['domid']]['cpu_time']) /
  184. long(1000**3) / (current_time-previous_time) * 100)
  185. if current[vm['domid']]['cpu_usage'] < 0:
  186. # VM has been rebooted
  187. current[vm['domid']]['cpu_usage'] = 0
  188. else:
  189. current[vm['domid']]['cpu_usage'] = 0
  190. return (current_time, current)
  191. class Label(object):
  192. '''Label definition for virtual machines
  193. Label specifies colour of the padlock displayed next to VM's name.
  194. When this is a :py:class:`qubes.vm.dispvm.DispVM`, padlock is overlayed
  195. with recycling pictogram.
  196. :param int index: numeric identificator of label
  197. :param str color: colour specification as in HTML (``#abcdef``)
  198. :param str name: label's name like "red" or "green"
  199. '''
  200. def __init__(self, index, color, name):
  201. #: numeric identificator of label
  202. self.index = index
  203. #: colour specification as in HTML (``#abcdef``)
  204. self.color = color
  205. #: label's name like "red" or "green"
  206. self.name = name
  207. #: freedesktop icon name, suitable for use in :py:meth:`PyQt4.QtGui.QIcon.fromTheme`
  208. self.icon = 'appvm-' + name
  209. #: freedesktop icon name, suitable for use in :py:meth:`PyQt4.QtGui.QIcon.fromTheme`
  210. #: on DispVMs
  211. self.icon_dispvm = 'dispvm-' + name
  212. @classmethod
  213. def fromxml(cls, xml):
  214. '''Create label definition from XML node
  215. :param lxml.etree._Element xml: XML node reference
  216. :rtype: :py:class:`qubes.Label`
  217. '''
  218. index = int(xml.get('id').split('-', 1)[1])
  219. color = xml.get('color')
  220. name = xml.text
  221. return cls(index, color, name)
  222. def __xml__(self):
  223. element = lxml.etree.Element('label', id='label-' + self.index, color=self.color)
  224. element.text = self.name
  225. return element
  226. def __repr__(self):
  227. return '{}({!r}, {!r}, {!r}, dispvm={!r})'.format(
  228. self.__class__.__name__,
  229. self.index,
  230. self.color,
  231. self.name)
  232. @__builtin__.property
  233. def icon_path(self):
  234. '''Icon path
  235. .. deprecated:: 2.0
  236. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  237. '''
  238. return os.path.join(system_path['qubes_icon_dir'], self.icon) + ".png"
  239. @__builtin__.property
  240. def icon_path_dispvm(self):
  241. '''Icon path
  242. .. deprecated:: 2.0
  243. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  244. '''
  245. return os.path.join(system_path['qubes_icon_dir'], self.icon_dispvm) + ".png"
  246. class VMCollection(object):
  247. '''A collection of Qubes VMs
  248. VMCollection supports ``in`` operator. You may test for ``qid``, ``name``
  249. and whole VM object's presence.
  250. Iterating over VMCollection will yield machine objects.
  251. '''
  252. def __init__(self, app):
  253. self.app = app
  254. self._dict = dict()
  255. def __repr__(self):
  256. return '<{} {!r}>'.format(self.__class__.__name__, list(sorted(self.keys())))
  257. def items(self):
  258. '''Iterate over ``(qid, vm)`` pairs'''
  259. for qid in self.qids():
  260. yield (qid, self[qid])
  261. def qids(self):
  262. '''Iterate over all qids
  263. qids are sorted by numerical order.
  264. '''
  265. return iter(sorted(self._dict.keys()))
  266. keys = qids
  267. def names(self):
  268. '''Iterate over all names
  269. names are sorted by lexical order.
  270. '''
  271. return iter(sorted(vm.name for vm in self._dict.values()))
  272. def vms(self):
  273. '''Iterate over all machines
  274. vms are sorted by qid.
  275. '''
  276. return iter(sorted(self._dict.values()))
  277. __iter__ = vms
  278. values = vms
  279. def add(self, value):
  280. '''Add VM to collection
  281. :param qubes.vm.BaseVM value: VM to add
  282. :raises TypeError: when value is of wrong type
  283. :raises ValueError: when there is already VM which has equal ``qid``
  284. '''
  285. # this violates duck typing, but is needed
  286. # for VMProperty to function correctly
  287. if not isinstance(value, qubes.vm.BaseVM):
  288. raise TypeError('{} holds only BaseVM instances'.format(self.__class__.__name__))
  289. if not hasattr(value, 'qid'):
  290. value.qid = self.domains.get_new_unused_qid()
  291. if value.qid in self:
  292. raise ValueError('This collection already holds VM that has qid={!r} (!r)'.format(
  293. value.qid, self[value.qid]))
  294. if value.name in self:
  295. raise ValueError('This collection already holds VM that has name={!r} (!r)'.format(
  296. value.name, self[value.name]))
  297. self._dict[value.qid] = value
  298. self.app.fire_event('domain-added', value)
  299. def __getitem__(self, key):
  300. if isinstance(key, int):
  301. return self._dict[key]
  302. if isinstance(key, basestring):
  303. for vm in self:
  304. if (vm.name == key):
  305. return vm
  306. raise KeyError(key)
  307. if isinstance(key, qubes.vm.BaseVM):
  308. if key in self:
  309. return key
  310. raise KeyError(key)
  311. raise KeyError(key)
  312. def __delitem__(self, key):
  313. vm = self[key]
  314. del self._dict[vm.qid]
  315. self.app.fire_event('domain-deleted', vm)
  316. def __contains__(self, key):
  317. return any((key == vm or key == vm.qid or key == vm.name) for vm in self)
  318. def __len__(self):
  319. return len(self._dict)
  320. def get_vms_based_on(self, template):
  321. template = self[template]
  322. return set(vm for vm in self if vm.template == template)
  323. def get_vms_connected_to(self, netvm):
  324. new_vms = set([netvm])
  325. dependend_vms = set()
  326. # Dependency resolving only makes sense on NetVM (or derivative)
  327. # if not self[netvm_qid].is_netvm():
  328. # return set([])
  329. while len(new_vms) > 0:
  330. cur_vm = new_vms.pop()
  331. for vm in cur_vm.connected_vms.values():
  332. if vm in dependend_vms:
  333. continue
  334. dependend_vms.add(vm.qid)
  335. # if vm.is_netvm():
  336. new_vms.append(vm.qid)
  337. return dependent_vms
  338. # XXX with Qubes Admin Api this will probably lead to race condition
  339. # whole process of creating and adding should be synchronised
  340. def get_new_unused_qid(self):
  341. used_ids = set(self.qids())
  342. for i in range(1, MAX_QID):
  343. if i not in used_ids:
  344. return i
  345. raise LookupError("Cannot find unused qid!")
  346. def get_new_unused_netid(self):
  347. used_ids = set([vm.netid for vm in self]) # if vm.is_netvm()])
  348. for i in range(1, MAX_NETID):
  349. if i not in used_ids:
  350. return i
  351. raise LookupError("Cannot find unused netid!")
  352. class property(object):
  353. '''Qubes property.
  354. This class holds one property that can be saved to and loaded from
  355. :file:`qubes.xml`. It is used for both global and per-VM properties.
  356. Property can be unset by ordinary ``del`` statement or assigning
  357. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  358. assignment/load) attempting to read a property will get its default value
  359. or, when no default, py:class:`exceptions.AttributeError`.
  360. :param str name: name of the property
  361. :param collections.Callable setter: if not :py:obj:`None`, this is used to initialise value; first parameter to the function is holder instance and the second is value; this is called before ``type``
  362. :param collections.Callable saver: function to coerce value to something readable by setter
  363. :param type type: if not :py:obj:`None`, value is coerced to this type
  364. :param object default: default value; if callable, will be called with holder as first argument
  365. :param int load_stage: stage when property should be loaded (see :py:class:`Qubes` for description of stages)
  366. :param int order: order of evaluation (bigger order values are later)
  367. :param str doc: docstring; this should be one paragraph of plain RST, no sphinx-specific features
  368. Setters and savers have following signatures:
  369. .. :py:function:: setter(self, prop, value)
  370. :noindex:
  371. :param self: instance of object that is holding property
  372. :param prop: property object
  373. :param value: value being assigned
  374. .. :py:function:: saver(self, prop, value)
  375. :noindex:
  376. :param self: instance of object that is holding property
  377. :param prop: property object
  378. :param value: value being saved
  379. :rtype: str
  380. :raises property.DontSave: when property should not be saved at all
  381. '''
  382. #: Assigning this value to property means setting it to its default value.
  383. #: If property has no default value, this will unset it.
  384. DEFAULT = object()
  385. # internal use only
  386. _NO_DEFAULT = object()
  387. def __init__(self, name, setter=None, saver=None, type=None, default=_NO_DEFAULT,
  388. load_stage=2, order=0, save_via_ref=False, doc=None):
  389. self.__name__ = name
  390. self._setter = setter
  391. self._saver = saver if saver is not None else (lambda self, prop, value: str(value))
  392. self._type = type
  393. self._default = default
  394. self.order = order
  395. self.load_stage = load_stage
  396. self.save_via_ref = save_via_ref
  397. self.__doc__ = doc
  398. self._attr_name = '_qubesprop_' + name
  399. def __get__(self, instance, owner):
  400. if instance is None:
  401. return self
  402. # XXX this violates duck typing, shall we keep it?
  403. if not isinstance(instance, PropertyHolder):
  404. raise AttributeError(
  405. 'qubes.property should be used on qubes.PropertyHolder instances only')
  406. try:
  407. return getattr(instance, self._attr_name)
  408. except AttributeError:
  409. if self._default is self._NO_DEFAULT:
  410. raise AttributeError('property {!r} not set'.format(self.__name__))
  411. elif isinstance(self._default, collections.Callable):
  412. return self._default(instance)
  413. else:
  414. return self._default
  415. def __set__(self, instance, value):
  416. if value is self.__class__.DEFAULT:
  417. self.__delete__(instance)
  418. return
  419. try:
  420. oldvalue = getattr(instance, self.__name__)
  421. has_oldvalue = True
  422. except AttributeError:
  423. has_oldvalue = False
  424. if self._setter is not None:
  425. value = self._setter(instance, self, value)
  426. if self._type is not None:
  427. value = self._type(value)
  428. if has_oldvalue:
  429. instance.fire_event_pre('property-pre-set:' + self.__name__, value, oldvalue)
  430. else:
  431. instance.fire_event_pre('property-pre-set:' + self.__name__, value)
  432. instance._init_property(self, value)
  433. if has_oldvalue:
  434. instance.fire_event('property-set:' + self.__name__, value, oldvalue)
  435. else:
  436. instance.fire_event('property-set:' + self.__name__, value)
  437. def __delete__(self, instance):
  438. try:
  439. oldvalue = getattr(instance, self.__name__)
  440. has_oldvalue = True
  441. except AttributeError:
  442. has_oldvalue = False
  443. if has_oldvalue:
  444. instance.fire_event_pre('property-pre-deleted:' + self.__name__, oldvalue)
  445. else:
  446. instance.fire_event_pre('property-pre-deleted:' + self.__name__)
  447. delattr(instance, self._attr_name)
  448. if has_oldvalue:
  449. instance.fire_event('property-deleted:' + self.__name__, oldvalue)
  450. else:
  451. instance.fire_event('property-deleted:' + self.__name__)
  452. def __repr__(self):
  453. return '<{} object at {:#x} name={!r} default={!r}>'.format(
  454. self.__class__.__name__, id(self), self.__name__, self._default)
  455. def __hash__(self):
  456. return hash(self.__name__)
  457. def __eq__(self, other):
  458. return self.__name__ == other.__name__
  459. def format_doc(self):
  460. '''Return parsed documentation string, stripping RST markup.
  461. '''
  462. if not self.__doc__: return ''
  463. output, pub = docutils.core.publish_programmatically(
  464. source_class=docutils.io.StringInput,
  465. source=' '.join(self.__doc__.strip().split()),
  466. source_path=None,
  467. destination_class=docutils.io.NullOutput, destination=None,
  468. destination_path=None,
  469. reader=None, reader_name='standalone',
  470. parser=None, parser_name='restructuredtext',
  471. writer=None, writer_name='null',
  472. settings=None, settings_spec=None, settings_overrides=None,
  473. config_section=None, enable_exit_status=None)
  474. return pub.writer.document.astext()
  475. #
  476. # exceptions
  477. #
  478. class DontSave(Exception):
  479. '''This exception may be raised from saver to sing that property should
  480. not be saved.
  481. '''
  482. pass
  483. @staticmethod
  484. def dontsave(self, prop, value):
  485. '''Dummy saver that never saves anything.'''
  486. raise DontSave()
  487. #
  488. # some setters provided
  489. #
  490. @staticmethod
  491. def forbidden(self, prop, value):
  492. '''Property setter that forbids loading a property.
  493. This is used to effectively disable property in classes which inherit
  494. unwanted property. When someone attempts to load such a property, it
  495. :throws AttributeError: always
  496. '''
  497. raise AttributeError('setting {} property on {} instance is forbidden'.format(
  498. prop.__name__, self.__class__.__name__))
  499. @staticmethod
  500. def bool(self, prop, value):
  501. '''Property setter for boolean properties.
  502. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  503. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  504. :py:obj:`True`.
  505. '''
  506. lcvalue = value.lower()
  507. if lcvalue in ('0', 'no', 'false'): return False
  508. if lcvalue in ('1', 'yes', 'true'): return True
  509. raise ValueError('Invalid literal for boolean property: {!r}'.format(value))
  510. class PropertyHolder(qubes.events.Emitter):
  511. '''Abstract class for holding :py:class:`qubes.property`
  512. Events fired by instances of this class:
  513. .. event:: property-load (subject, event)
  514. Fired once after all properties are loaded from XML. Individual
  515. ``property-set`` events are not fired.
  516. .. event:: property-set:<propname> (subject, event, name, newvalue[, oldvalue])
  517. Fired when property changes state. Signature is variable,
  518. *oldvalue* is present only if there was an old value.
  519. :param name: Property name
  520. :param newvalue: New value of the property
  521. :param oldvalue: Old value of the property
  522. .. event:: property-pre-set:<propname> (subject, event, name, newvalue[, oldvalue])
  523. Fired before property changes state. Signature is variable,
  524. *oldvalue* is present only if there was an old value.
  525. :param name: Property name
  526. :param newvalue: New value of the property
  527. :param oldvalue: Old value of the property
  528. .. event:: property-del:<propname> (subject, event, name[, oldvalue])
  529. Fired when property gets deleted (is set to default). Signature is
  530. variable, *oldvalue* is present only if there was an old value.
  531. :param name: Property name
  532. :param oldvalue: Old value of the property
  533. .. event:: property-pre-del:<propname> (subject, event, name[, oldvalue])
  534. Fired before property gets deleted (is set to default). Signature
  535. is variable, *oldvalue* is present only if there was an old value.
  536. :param name: Property name
  537. :param oldvalue: Old value of the property
  538. Members:
  539. '''
  540. def __init__(self, xml, *args, **kwargs):
  541. super(PropertyHolder, self).__init__(*args, **kwargs)
  542. self.xml = xml
  543. @classmethod
  544. def get_props_list(cls, load_stage=None):
  545. '''List all properties attached to this VM's class
  546. :param load_stage: Filter by load stage
  547. :type load_stage: :py:func:`int` or :py:obj:`None`
  548. '''
  549. props = set()
  550. for class_ in cls.__mro__:
  551. props.update(prop for prop in class_.__dict__.values()
  552. if isinstance(prop, property))
  553. if load_stage is not None:
  554. props = set(prop for prop in props
  555. if prop.load_stage == load_stage)
  556. return sorted(props, key=lambda prop: (prop.load_stage, prop.order, prop.__name__))
  557. def _init_property(self, prop, value):
  558. '''Initialise property to a given value, without side effects.
  559. :param qubes.property prop: property object of particular interest
  560. :param value: value
  561. '''
  562. setattr(self, self.get_property_def(prop)._attr_name, value)
  563. def property_is_default(self, prop):
  564. '''Check whether property is in it's default value.
  565. Properties when unset may return some default value, so
  566. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  567. method allows for checking if the value returned is in fact it's
  568. default value.
  569. :param qubes.property prop: property object of particular interest
  570. :rtype: bool
  571. '''
  572. return hasattr(self, self.get_property_def(prop)._attr_name)
  573. @classmethod
  574. def get_property_def(cls, prop):
  575. '''Return property definition object.
  576. If prop is already :py:class:`qubes.property` instance, return the same
  577. object.
  578. :param prop: property object or name
  579. :type prop: qubes.property or str
  580. :rtype: qubes.property
  581. '''
  582. if isinstance(prop, qubes.property):
  583. return prop
  584. for p in cls.get_props_list():
  585. if p.__name__ == prop:
  586. return p
  587. raise AttributeError('No property {!r} found in {!r}'.format(
  588. prop, cls))
  589. def load_properties(self, load_stage=None):
  590. '''Load properties from immediate children of XML node.
  591. ``property-set`` events are not fired for each individual property.
  592. :param lxml.etree._Element xml: XML node reference
  593. '''
  594. self.events_enabled = False
  595. all_names = set(prop.__name__ for prop in self.get_props_list(load_stage))
  596. for node in self.xml.xpath('./properties/property'):
  597. name = node.get('name')
  598. value = node.get('ref') or node.text
  599. if not name in all_names:
  600. raise AttributeError(
  601. 'No property {!r} found in {!r}'.format(
  602. name, self.__class__))
  603. setattr(self, name, value)
  604. self.events_enabled = True
  605. self.fire_event('property-loaded')
  606. def save_properties(self, with_defaults=False):
  607. '''Iterator that yields XML nodes representing set properties.
  608. :param bool with_defaults: If :py:obj:`True`, then it also includes properties which were not set explicite, but have default values filled.
  609. '''
  610. properties = lxml.etree.Element('properties')
  611. for prop in self.get_props_list():
  612. try:
  613. value = getattr(self, (prop.__name__ if with_defaults else prop._attr_name))
  614. except AttributeError, e:
  615. continue
  616. try:
  617. value = prop._saver(self, prop, value)
  618. except property.DontSave:
  619. continue
  620. element = lxml.etree.Element('property', name=prop.__name__)
  621. if prop.save_via_ref:
  622. element.set('ref', value)
  623. else:
  624. element.text = value
  625. properties.append(element)
  626. return properties
  627. # this was clone_attrs
  628. def clone_properties(self, src, proplist=None):
  629. '''Clone properties from other object.
  630. :param PropertyHolder src: source object
  631. :param list proplist: list of properties (:py:obj:`None` for all properties)
  632. '''
  633. if proplist is None:
  634. proplist = self.get_props_list()
  635. else:
  636. proplist = [prop for prop in self.get_props_list()
  637. if prop.__name__ in proplist or prop in proplist]
  638. for prop in self.proplist():
  639. try:
  640. self._init_property(self, prop, getattr(src, prop._attr_name))
  641. except AttributeError:
  642. continue
  643. self.fire_event('cloned-properties', src, proplist)
  644. def require_property(self, prop, allow_none=False, hard=False):
  645. '''Complain badly when property is not set.
  646. :param prop: property name or object
  647. :type prop: qubes.property or str
  648. :param bool allow_none: if :py:obj:`True`, don't complain if :py:obj:`None` is found
  649. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; if :py:obj:`False`, log warning instead
  650. '''
  651. if isinstance(qubes.property, prop):
  652. prop = prop.__name__
  653. try:
  654. value = getattr(self, prop)
  655. if value is None and not allow_none:
  656. raise AttributeError()
  657. except AttributeError:
  658. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  659. if hard:
  660. raise AssertionError(msg)
  661. else:
  662. self.log(msg)
  663. import qubes.vm
  664. class VMProperty(property):
  665. '''Property that is referring to a VM
  666. :param type vmclass: class that returned VM is supposed to be instance of
  667. and all supported by :py:class:`property` with the exception of ``type`` and ``setter``
  668. '''
  669. def __init__(self, name, vmclass=qubes.vm.BaseVM, allow_none=False, **kwargs):
  670. if 'type' in kwargs:
  671. raise TypeError("'type' keyword parameter is unsupported in {}".format(
  672. self.__class__.__name__))
  673. if 'setter' in kwargs:
  674. raise TypeError("'setter' keyword parameter is unsupported in {}".format(
  675. self.__class__.__name__))
  676. if not issubclass(vmclass, qubes.vm.BaseVM):
  677. raise TypeError("'vmclass' should specify a subclass of qubes.vm.BaseVM")
  678. super(VMProperty, self).__init__(name, **kwargs)
  679. self.vmclass = vmclass
  680. self.allow_none = allow_none
  681. def __set__(self, instance, value):
  682. if value is None:
  683. if self.allow_none:
  684. super(VMProperty, self).__set__(self, instance, vm)
  685. return
  686. else:
  687. raise ValueError(
  688. 'Property {!r} does not allow setting to {!r}'.format(
  689. self.__name__, value))
  690. # XXX this may throw LookupError; that's good until introduction
  691. # of QubesNoSuchVMException or whatever
  692. vm = instance.app.domains[value]
  693. if not isinstance(vm, self.vmclass):
  694. raise TypeError('wrong VM class: domains[{!r}] if of type {!s} and not {!s}'.format(
  695. value, vm.__class__.__name__, self.vmclass.__name__))
  696. super(VMProperty, self).__set__(self, instance, vm)
  697. import qubes.vm.qubesvm
  698. import qubes.vm.templatevm
  699. class Qubes(PropertyHolder):
  700. '''Main Qubes application
  701. :param str store: path to ``qubes.xml``
  702. The store is loaded in stages:
  703. 1. In the first stage there are loaded some basic features from store
  704. (currently labels).
  705. 2. In the second stage stubs for all VMs are loaded. They are filled
  706. with their basic properties, like ``qid`` and ``name``.
  707. 3. In the third stage all global properties are loaded. They often
  708. reference VMs, like default netvm, so they should be filled after
  709. loading VMs.
  710. 4. In the fourth stage all remaining VM properties are loaded. They
  711. also need all VMs loaded, because they represent dependencies
  712. between VMs like aforementioned netvm.
  713. 5. In the fifth stage there are some fixups to ensure sane system
  714. operation.
  715. This class emits following events:
  716. .. event:: domain-added (subject, event, vm)
  717. When domain is added.
  718. :param subject: Event emitter
  719. :param event: Event name (``'domain-added'``)
  720. :param vm: Domain object
  721. .. event:: domain-deleted (subject, event, vm)
  722. When domain is deleted. VM still has reference to ``app`` object,
  723. but is not contained within VMCollection.
  724. :param subject: Event emitter
  725. :param event: Event name (``'domain-deleted'``)
  726. :param vm: Domain object
  727. Methods and attributes:
  728. '''
  729. default_netvm = VMProperty('default_netvm', load_stage=3, default=None,
  730. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  731. that AppVMs are not connected to the Internet.''')
  732. default_fw_netvm = VMProperty('default_fw_netvm', load_stage=3, default=None,
  733. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  734. that ProxyVMs (including FirewallVM) are not connected to the
  735. Internet.''')
  736. default_template = VMProperty('default_template', load_stage=3,
  737. vmclass=qubes.vm.templatevm.TemplateVM,
  738. doc='Default template for new AppVMs')
  739. updatevm = VMProperty('updatevm', load_stage=3,
  740. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  741. TemplateVMs''')
  742. clockvm = VMProperty('clockvm', load_stage=3,
  743. doc='Which VM to use as NTP proxy for updating AdminVM')
  744. default_kernel = property('default_kernel', load_stage=3,
  745. doc='Which kernel to use when not overriden in VM')
  746. def __init__(self, store='/var/lib/qubes/qubes.xml'):
  747. self._extensions = set(ext(self) for ext in qubes.ext.Extension.register.values())
  748. #: collection of all VMs managed by this Qubes instance
  749. self.domains = VMCollection()
  750. #: collection of all available labels for VMs
  751. self.labels = {}
  752. #: Connection to VMM
  753. self.vmm = VMMConnection()
  754. #: Information about host system
  755. self.host = QubesHost(self)
  756. self._store = store
  757. try:
  758. self.load()
  759. except IOError:
  760. self._init()
  761. super(Qubes, self).__init__(xml=lxml.etree.parse(self.qubes_store_file))
  762. def _open_store(self):
  763. if hasattr(self, '_storefd'):
  764. return
  765. self._storefd = open(self._store, 'r+')
  766. if os.name == 'posix':
  767. fcntl.lockf (self.qubes_store_file, fcntl.LOCK_EX)
  768. elif os.name == 'nt':
  769. overlapped = pywintypes.OVERLAPPED()
  770. win32file.LockFileEx(win32file._get_osfhandle(self.qubes_store_file.fileno()),
  771. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  772. def load(self):
  773. '''
  774. :throws EnvironmentError: failure on parsing store
  775. :throws xml.parsers.expat.ExpatError: failure on parsing store
  776. '''
  777. self._open_store()
  778. # stage 1: load labels
  779. for node in self._xml.xpath('./labels/label'):
  780. label = Label.fromxml(node)
  781. self.labels[label.id] = label
  782. # stage 2: load VMs
  783. for node in self._xml.xpath('./domains/domain'):
  784. cls = qubes.vm.load(node.get("class"))
  785. vm = cls.fromxml(self, node)
  786. self.domains.add(vm)
  787. if not 0 in self.domains:
  788. self.domains.add(qubes.vm.adminvm.AdminVM(self))
  789. # stage 3: load global properties
  790. self.load_properties(self.xml, load_stage=3)
  791. # stage 4: fill all remaining VM properties
  792. for vm in self.domains:
  793. vm.load_properties(None, load_stage=4)
  794. # stage 5: misc fixups
  795. self.require_property('default_fw_netvm', allow_none=True)
  796. self.require_property('default_netvm', allow_none=True)
  797. self.require_property('default_template')
  798. self.require_property('clockvm')
  799. self.require_property('updatevm')
  800. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  801. # using 123/udp port)
  802. if hasattr(self, 'clockvm'):
  803. if 'ntpd' in self.clockvm.services:
  804. if self.clockvm.services['ntpd']:
  805. self.log.warning("VM set as clockvm ({!r}) has enabled "
  806. "'ntpd' service! Expect failure when syncing time in "
  807. "dom0.".format(self.clockvm))
  808. else:
  809. self.clockvm.services['ntpd'] = False
  810. def _init(self):
  811. self._open_store()
  812. self.labels = {
  813. 1: Label(1, '0xcc0000', 'red'),
  814. 2: Label(2, '0xf57900', 'orange'),
  815. 3: Label(3, '0xedd400', 'yellow'),
  816. 4: Label(4, '0x73d216', 'green'),
  817. 5: Label(5, '0x555753', 'gray'),
  818. 6: Label(6, '0x3465a4', 'blue'),
  819. 7: Label(7, '0x75507b', 'purple'),
  820. 8: Label(8, '0x000000', 'black'),
  821. }
  822. def __del__(self):
  823. # intentionally do not call explicit unlock to not unlock the file
  824. # before all buffers are flushed
  825. self._storefd.close()
  826. del self._storefd
  827. def __xml__(self):
  828. element = lxml.etree.Element('qubes')
  829. element.append(self.save_labels())
  830. element.append(self.save_properties())
  831. domains = lxml.etree.Element('domains')
  832. for vm in self.domains:
  833. domains.append(vm.__xml__())
  834. element.append(domains)
  835. return element
  836. def save(self):
  837. '''Save all data to qubes.xml
  838. '''
  839. self._storefd.seek(0)
  840. self._storefd.truncate()
  841. lxml.etree.ElementTree(self.__xml__()).write(
  842. self._storefd, encoding='utf-8', pretty_print=True)
  843. self._storefd.sync()
  844. os.chmod(self._store, 0660)
  845. os.chown(self._store, -1, grp.getgrnam('qubes').gr_gid)
  846. def save_labels(self):
  847. '''Serialise labels
  848. :rtype: lxml.etree._Element
  849. '''
  850. labels = lxml.etree.Element('labels')
  851. for label in self.labels:
  852. labels.append(label.__xml__())
  853. return labels
  854. def add_new_vm(self, vm):
  855. '''Add new Virtual Machine to colletion
  856. '''
  857. self.domains.add(vm)
  858. @qubes.events.handler('domain-pre-deleted')
  859. def on_domain_pre_deleted(self, event, vm):
  860. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  861. appvms = self.get_vms_based_on(vm)
  862. if appvms:
  863. raise QubesException(
  864. 'Cannot remove template that has dependent AppVMs. '
  865. 'Affected are: {}'.format(', '.join(
  866. vm.name for name in sorted(appvms))))
  867. @qubes.events.handler('domain-deleted')
  868. def on_domain_deleted(self, event, vm):
  869. if self.default_netvm == vm:
  870. del self.default_netvm
  871. if self.default_fw_netvm == vm:
  872. del self.default_fw_netvm
  873. if self.clockvm == vm:
  874. del self.clockvm
  875. if self.updatevm == vm:
  876. del self.updatevm
  877. if self.default_template == vm:
  878. del self.default_template
  879. return super(QubesVmCollection, self).pop(qid)
  880. @qubes.events.handler('property-pre-set:clockvm')
  881. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  882. if 'ntpd' in newvalue.services:
  883. if newvalue.services['ntpd']:
  884. raise QubesException(
  885. 'Cannot set {!r} as {!r} property since it has ntpd enabled.'.format(
  886. newvalue, name))
  887. else:
  888. newvalue.services['ntpd'] = False
  889. @qubes.events.handler('property-pre-set:default_netvm')
  890. def on_property_pre_set_default_netvm(self, event, name, newvalue, oldvalue=None):
  891. if newvalue is not None and oldvalue is not None \
  892. and oldvalue.is_running() and not newvalue.is_running() \
  893. and self.domains.get_vms_connected_to(oldvalue):
  894. raise QubesException(
  895. 'Cannot change default_netvm to domain that is not running ({!r}).'.format(
  896. newvalue))
  897. @qubes.events.handler('property-set:default_fw_netvm')
  898. def on_property_set_default_netvm(self, event, name, newvalue, oldvalue=None):
  899. for vm in self.domains:
  900. if not vm.provides_network and vm.property_is_default('netvm'):
  901. # fire property-del:netvm as it is responsible for resetting
  902. # netvm to it's default value
  903. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  904. @qubes.events.handler('property-set:default_netvm')
  905. def on_property_set_default_netvm(self, event, name, newvalue, oldvalue=None):
  906. for vm in self.domains:
  907. if vm.provides_network and vm.property_is_default('netvm'):
  908. # fire property-del:netvm as it is responsible for resetting
  909. # netvm to it's default value
  910. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  911. # load plugins
  912. import qubes._pluginloader