__init__.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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. # sys.stderr.write('{!r}.__get__({}, {!r})\n'.format(self.__name__, hex(id(instance)), owner))
  401. if instance is None:
  402. return self
  403. # XXX this violates duck typing, shall we keep it?
  404. if not isinstance(instance, PropertyHolder):
  405. raise AttributeError(
  406. 'qubes.property should be used on qubes.PropertyHolder instances only')
  407. # sys.stderr.write(' __get__ try\n')
  408. try:
  409. return getattr(instance, self._attr_name)
  410. except AttributeError:
  411. # sys.stderr.write(' __get__ except\n')
  412. if self._default is self._NO_DEFAULT:
  413. raise AttributeError('property {!r} not set'.format(self.__name__))
  414. elif isinstance(self._default, collections.Callable):
  415. return self._default(instance)
  416. else:
  417. return self._default
  418. def __set__(self, instance, value):
  419. if value is self.__class__.DEFAULT:
  420. self.__delete__(instance)
  421. return
  422. try:
  423. oldvalue = getattr(instance, self.__name__)
  424. has_oldvalue = True
  425. except AttributeError:
  426. has_oldvalue = False
  427. if self._setter is not None:
  428. value = self._setter(instance, self, value)
  429. if self._type is not None:
  430. value = self._type(value)
  431. if has_oldvalue:
  432. instance.fire_event_pre('property-pre-set:' + self.__name__, value, oldvalue)
  433. else:
  434. instance.fire_event_pre('property-pre-set:' + self.__name__, value)
  435. instance._init_property(self, value)
  436. if has_oldvalue:
  437. instance.fire_event('property-set:' + self.__name__, value, oldvalue)
  438. else:
  439. instance.fire_event('property-set:' + self.__name__, value)
  440. def __delete__(self, instance):
  441. try:
  442. oldvalue = getattr(instance, self.__name__)
  443. has_oldvalue = True
  444. except AttributeError:
  445. has_oldvalue = False
  446. if has_oldvalue:
  447. instance.fire_event_pre('property-pre-deleted:' + self.__name__, oldvalue)
  448. else:
  449. instance.fire_event_pre('property-pre-deleted:' + self.__name__)
  450. delattr(instance, self._attr_name)
  451. if has_oldvalue:
  452. instance.fire_event('property-deleted:' + self.__name__, oldvalue)
  453. else:
  454. instance.fire_event('property-deleted:' + self.__name__)
  455. def __repr__(self):
  456. return '<{} object at {:#x} name={!r} default={!r}>'.format(
  457. self.__class__.__name__, id(self), self.__name__, self._default)
  458. def __hash__(self):
  459. return hash(self.__name__)
  460. def __eq__(self, other):
  461. return self.__name__ == other.__name__
  462. def format_doc(self):
  463. '''Return parsed documentation string, stripping RST markup.
  464. '''
  465. if not self.__doc__: return ''
  466. output, pub = docutils.core.publish_programmatically(
  467. source_class=docutils.io.StringInput,
  468. source=' '.join(self.__doc__.strip().split()),
  469. source_path=None,
  470. destination_class=docutils.io.NullOutput, destination=None,
  471. destination_path=None,
  472. reader=None, reader_name='standalone',
  473. parser=None, parser_name='restructuredtext',
  474. writer=None, writer_name='null',
  475. settings=None, settings_spec=None, settings_overrides=None,
  476. config_section=None, enable_exit_status=None)
  477. return pub.writer.document.astext()
  478. #
  479. # exceptions
  480. #
  481. class DontSave(Exception):
  482. '''This exception may be raised from saver to sing that property should
  483. not be saved.
  484. '''
  485. pass
  486. @staticmethod
  487. def dontsave(self, prop, value):
  488. '''Dummy saver that never saves anything.'''
  489. raise DontSave()
  490. #
  491. # some setters provided
  492. #
  493. @staticmethod
  494. def forbidden(self, prop, value):
  495. '''Property setter that forbids loading a property.
  496. This is used to effectively disable property in classes which inherit
  497. unwanted property. When someone attempts to load such a property, it
  498. :throws AttributeError: always
  499. '''
  500. raise AttributeError('setting {} property on {} instance is forbidden'.format(
  501. prop.__name__, self.__class__.__name__))
  502. @staticmethod
  503. def bool(self, prop, value):
  504. '''Property setter for boolean properties.
  505. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  506. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  507. :py:obj:`True`.
  508. '''
  509. lcvalue = value.lower()
  510. if lcvalue in ('0', 'no', 'false'): return False
  511. if lcvalue in ('1', 'yes', 'true'): return True
  512. raise ValueError('Invalid literal for boolean property: {!r}'.format(value))
  513. class PropertyHolder(qubes.events.Emitter):
  514. '''Abstract class for holding :py:class:`qubes.property`
  515. Events fired by instances of this class:
  516. .. event:: property-load (subject, event)
  517. Fired once after all properties are loaded from XML. Individual
  518. ``property-set`` events are not fired.
  519. .. event:: property-set:<propname> (subject, event, name, newvalue[, oldvalue])
  520. Fired when property changes state. Signature is variable,
  521. *oldvalue* is present only if there was an old value.
  522. :param name: Property name
  523. :param newvalue: New value of the property
  524. :param oldvalue: Old value of the property
  525. .. event:: property-pre-set:<propname> (subject, event, name, newvalue[, oldvalue])
  526. Fired before property changes state. Signature is variable,
  527. *oldvalue* is present only if there was an old value.
  528. :param name: Property name
  529. :param newvalue: New value of the property
  530. :param oldvalue: Old value of the property
  531. .. event:: property-del:<propname> (subject, event, name[, oldvalue])
  532. Fired when property gets deleted (is set to default). Signature is
  533. variable, *oldvalue* is present only if there was an old value.
  534. :param name: Property name
  535. :param oldvalue: Old value of the property
  536. .. event:: property-pre-del:<propname> (subject, event, name[, oldvalue])
  537. Fired before property gets deleted (is set to default). Signature
  538. is variable, *oldvalue* is present only if there was an old value.
  539. :param name: Property name
  540. :param oldvalue: Old value of the property
  541. Members:
  542. '''
  543. def __init__(self, xml, *args, **kwargs):
  544. super(PropertyHolder, self).__init__(*args, **kwargs)
  545. self.xml = xml
  546. @classmethod
  547. def get_props_list(cls, load_stage=None):
  548. '''List all properties attached to this VM's class
  549. :param load_stage: Filter by load stage
  550. :type load_stage: :py:func:`int` or :py:obj:`None`
  551. '''
  552. # sys.stderr.write('{!r}.get_props_list(load_stage={})\n'.format('self', load_stage))
  553. props = set()
  554. for class_ in cls.__mro__:
  555. props.update(prop for prop in class_.__dict__.values()
  556. if isinstance(prop, property))
  557. if load_stage is not None:
  558. props = set(prop for prop in props
  559. if prop.load_stage == load_stage)
  560. # sys.stderr.write(' props={!r}\n'.format(props))
  561. return sorted(props, key=lambda prop: (prop.load_stage, prop.order, prop.__name__))
  562. def _init_property(self, prop, value):
  563. '''Initialise property to a given value, without side effects.
  564. :param qubes.property prop: property object of particular interest
  565. :param value: value
  566. '''
  567. setattr(self, self.get_property_def(prop)._attr_name, value)
  568. def property_is_default(self, prop):
  569. '''Check whether property is in it's default value.
  570. Properties when unset may return some default value, so
  571. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  572. method allows for checking if the value returned is in fact it's
  573. default value.
  574. :param qubes.property prop: property object of particular interest
  575. :rtype: bool
  576. '''
  577. return hasattr(self, self.get_property_def(prop)._attr_name)
  578. @classmethod
  579. def get_property_def(cls, prop):
  580. '''Return property definition object.
  581. If prop is already :py:class:`qubes.property` instance, return the same
  582. object.
  583. :param prop: property object or name
  584. :type prop: qubes.property or str
  585. :rtype: qubes.property
  586. '''
  587. if isinstance(prop, qubes.property):
  588. return prop
  589. for p in cls.get_props_list():
  590. if p.__name__ == prop:
  591. return p
  592. raise AttributeError('No property {!r} found in {!r}'.format(
  593. prop, cls))
  594. def load_properties(self, load_stage=None):
  595. '''Load properties from immediate children of XML node.
  596. ``property-set`` events are not fired for each individual property.
  597. :param lxml.etree._Element xml: XML node reference
  598. '''
  599. # sys.stderr.write('<{}>.load_properties(load_stage={}) xml={!r}\n'.format(hex(id(self)), load_stage, self.xml))
  600. self.events_enabled = False
  601. all_names = set(prop.__name__ for prop in self.get_props_list(load_stage))
  602. # sys.stderr.write(' all_names={!r}\n'.format(all_names))
  603. for node in self.xml.xpath('./properties/property'):
  604. name = node.get('name')
  605. value = node.get('ref') or node.text
  606. # sys.stderr.write(' load_properties name={!r} value={!r}\n'.format(name, value))
  607. if not name in all_names:
  608. raise AttributeError(
  609. 'No property {!r} found in {!r}'.format(
  610. name, self.__class__))
  611. setattr(self, name, value)
  612. self.events_enabled = True
  613. self.fire_event('property-loaded')
  614. # sys.stderr.write(' load_properties return\n')
  615. def save_properties(self, with_defaults=False):
  616. '''Iterator that yields XML nodes representing set properties.
  617. :param bool with_defaults: If :py:obj:`True`, then it also includes properties which were not set explicite, but have default values filled.
  618. '''
  619. # sys.stderr.write('{!r}.save_properties(with_defaults={})\n'.format(self, with_defaults))
  620. properties = lxml.etree.Element('properties')
  621. for prop in self.get_props_list():
  622. try:
  623. value = getattr(self, (prop.__name__ if with_defaults else prop._attr_name))
  624. except AttributeError, e:
  625. # sys.stderr.write('AttributeError: {!s}\n'.format(e))
  626. continue
  627. try:
  628. value = prop._saver(self, prop, value)
  629. except property.DontSave:
  630. continue
  631. element = lxml.etree.Element('property', name=prop.__name__)
  632. if prop.save_via_ref:
  633. element.set('ref', value)
  634. else:
  635. element.text = value
  636. properties.append(element)
  637. return properties
  638. # this was clone_attrs
  639. def clone_properties(self, src, proplist=None):
  640. '''Clone properties from other object.
  641. :param PropertyHolder src: source object
  642. :param list proplist: list of properties (:py:obj:`None` for all properties)
  643. '''
  644. if proplist is None:
  645. proplist = self.get_props_list()
  646. else:
  647. proplist = [prop for prop in self.get_props_list()
  648. if prop.__name__ in proplist or prop in proplist]
  649. for prop in self.proplist():
  650. try:
  651. self._init_property(self, prop, getattr(src, prop._attr_name))
  652. except AttributeError:
  653. continue
  654. self.fire_event('cloned-properties', src, proplist)
  655. def require_property(self, prop, allow_none=False, hard=False):
  656. '''Complain badly when property is not set.
  657. :param prop: property name or object
  658. :type prop: qubes.property or str
  659. :param bool allow_none: if :py:obj:`True`, don't complain if :py:obj:`None` is found
  660. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; if :py:obj:`False`, log warning instead
  661. '''
  662. if isinstance(qubes.property, prop):
  663. prop = prop.__name__
  664. try:
  665. value = getattr(self, prop)
  666. if value is None and not allow_none:
  667. raise AttributeError()
  668. except AttributeError:
  669. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  670. if hard:
  671. raise AssertionError(msg)
  672. else:
  673. self.log(msg)
  674. import qubes.vm
  675. class VMProperty(property):
  676. '''Property that is referring to a VM
  677. :param type vmclass: class that returned VM is supposed to be instance of
  678. and all supported by :py:class:`property` with the exception of ``type`` and ``setter``
  679. '''
  680. def __init__(self, name, vmclass=qubes.vm.BaseVM, allow_none=False, **kwargs):
  681. if 'type' in kwargs:
  682. raise TypeError("'type' keyword parameter is unsupported in {}".format(
  683. self.__class__.__name__))
  684. if 'setter' in kwargs:
  685. raise TypeError("'setter' keyword parameter is unsupported in {}".format(
  686. self.__class__.__name__))
  687. if not issubclass(vmclass, qubes.vm.BaseVM):
  688. raise TypeError("'vmclass' should specify a subclass of qubes.vm.BaseVM")
  689. super(VMProperty, self).__init__(name, **kwargs)
  690. self.vmclass = vmclass
  691. self.allow_none = allow_none
  692. def __set__(self, instance, value):
  693. if value is None:
  694. if self.allow_none:
  695. super(VMProperty, self).__set__(self, instance, vm)
  696. return
  697. else:
  698. raise ValueError(
  699. 'Property {!r} does not allow setting to {!r}'.format(
  700. self.__name__, value))
  701. # XXX this may throw LookupError; that's good until introduction
  702. # of QubesNoSuchVMException or whatever
  703. vm = instance.app.domains[value]
  704. if not isinstance(vm, self.vmclass):
  705. raise TypeError('wrong VM class: domains[{!r}] if of type {!s} and not {!s}'.format(
  706. value, vm.__class__.__name__, self.vmclass.__name__))
  707. super(VMProperty, self).__set__(self, instance, vm)
  708. import qubes.vm.qubesvm
  709. import qubes.vm.templatevm
  710. class Qubes(PropertyHolder):
  711. '''Main Qubes application
  712. :param str store: path to ``qubes.xml``
  713. The store is loaded in stages:
  714. 1. In the first stage there are loaded some basic features from store
  715. (currently labels).
  716. 2. In the second stage stubs for all VMs are loaded. They are filled
  717. with their basic properties, like ``qid`` and ``name``.
  718. 3. In the third stage all global properties are loaded. They often
  719. reference VMs, like default netvm, so they should be filled after
  720. loading VMs.
  721. 4. In the fourth stage all remaining VM properties are loaded. They
  722. also need all VMs loaded, because they represent dependencies
  723. between VMs like aforementioned netvm.
  724. 5. In the fifth stage there are some fixups to ensure sane system
  725. operation.
  726. This class emits following events:
  727. .. event:: domain-added (subject, event, vm)
  728. When domain is added.
  729. :param subject: Event emitter
  730. :param event: Event name (``'domain-added'``)
  731. :param vm: Domain object
  732. .. event:: domain-deleted (subject, event, vm)
  733. When domain is deleted. VM still has reference to ``app`` object,
  734. but is not contained within VMCollection.
  735. :param subject: Event emitter
  736. :param event: Event name (``'domain-deleted'``)
  737. :param vm: Domain object
  738. Methods and attributes:
  739. '''
  740. default_netvm = VMProperty('default_netvm', load_stage=3, default=None,
  741. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  742. that AppVMs are not connected to the Internet.''')
  743. default_fw_netvm = VMProperty('default_fw_netvm', load_stage=3, default=None,
  744. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  745. that ProxyVMs (including FirewallVM) are not connected to the
  746. Internet.''')
  747. default_template = VMProperty('default_template', load_stage=3,
  748. vmclass=qubes.vm.templatevm.TemplateVM,
  749. doc='Default template for new AppVMs')
  750. updatevm = VMProperty('updatevm', load_stage=3,
  751. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  752. TemplateVMs''')
  753. clockvm = VMProperty('clockvm', load_stage=3,
  754. doc='Which VM to use as NTP proxy for updating AdminVM')
  755. default_kernel = property('default_kernel', load_stage=3,
  756. doc='Which kernel to use when not overriden in VM')
  757. def __init__(self, store='/var/lib/qubes/qubes.xml'):
  758. self._extensions = set(ext(self) for ext in qubes.ext.Extension.register.values())
  759. #: collection of all VMs managed by this Qubes instance
  760. self.domains = VMCollection()
  761. #: collection of all available labels for VMs
  762. self.labels = {}
  763. #: Connection to VMM
  764. self.vmm = VMMConnection()
  765. #: Information about host system
  766. self.host = QubesHost(self)
  767. self._store = store
  768. try:
  769. self.load()
  770. except IOError:
  771. self._init()
  772. super(Qubes, self).__init__(xml=lxml.etree.parse(self.qubes_store_file))
  773. def _open_store(self):
  774. if hasattr(self, '_storefd'):
  775. return
  776. self._storefd = open(self._store, 'r+')
  777. if os.name == 'posix':
  778. fcntl.lockf (self.qubes_store_file, fcntl.LOCK_EX)
  779. elif os.name == 'nt':
  780. overlapped = pywintypes.OVERLAPPED()
  781. win32file.LockFileEx(win32file._get_osfhandle(self.qubes_store_file.fileno()),
  782. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  783. def load(self):
  784. '''
  785. :throws EnvironmentError: failure on parsing store
  786. :throws xml.parsers.expat.ExpatError: failure on parsing store
  787. '''
  788. self._open_store()
  789. # stage 1: load labels
  790. for node in self._xml.xpath('./labels/label'):
  791. label = Label.fromxml(node)
  792. self.labels[label.id] = label
  793. # stage 2: load VMs
  794. for node in self._xml.xpath('./domains/domain'):
  795. cls = qubes.vm.load(node.get("class"))
  796. vm = cls.fromxml(self, node)
  797. self.domains.add(vm)
  798. if not 0 in self.domains:
  799. self.domains.add(qubes.vm.adminvm.AdminVM(self))
  800. # stage 3: load global properties
  801. self.load_properties(self.xml, load_stage=3)
  802. # stage 4: fill all remaining VM properties
  803. for vm in self.domains:
  804. vm.load_properties(None, load_stage=4)
  805. # stage 5: misc fixups
  806. self.require_property('default_fw_netvm', allow_none=True)
  807. self.require_property('default_netvm', allow_none=True)
  808. self.require_property('default_template')
  809. self.require_property('clockvm')
  810. self.require_property('updatevm')
  811. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  812. # using 123/udp port)
  813. if hasattr(self, 'clockvm'):
  814. if 'ntpd' in self.clockvm.services:
  815. if self.clockvm.services['ntpd']:
  816. self.log.warning("VM set as clockvm ({!r}) has enabled "
  817. "'ntpd' service! Expect failure when syncing time in "
  818. "dom0.".format(self.clockvm))
  819. else:
  820. self.clockvm.services['ntpd'] = False
  821. def _init(self):
  822. self._open_store()
  823. self.labels = {
  824. 1: Label(1, '0xcc0000', 'red'),
  825. 2: Label(2, '0xf57900', 'orange'),
  826. 3: Label(3, '0xedd400', 'yellow'),
  827. 4: Label(4, '0x73d216', 'green'),
  828. 5: Label(5, '0x555753', 'gray'),
  829. 6: Label(6, '0x3465a4', 'blue'),
  830. 7: Label(7, '0x75507b', 'purple'),
  831. 8: Label(8, '0x000000', 'black'),
  832. }
  833. def __del__(self):
  834. # intentionally do not call explicit unlock to not unlock the file
  835. # before all buffers are flushed
  836. self._storefd.close()
  837. del self._storefd
  838. def __xml__(self):
  839. element = lxml.etree.Element('qubes')
  840. element.append(self.save_labels())
  841. element.append(self.save_properties())
  842. domains = lxml.etree.Element('domains')
  843. for vm in self.domains:
  844. domains.append(vm.__xml__())
  845. element.append(domains)
  846. return element
  847. def save(self):
  848. '''Save all data to qubes.xml
  849. '''
  850. self._storefd.seek(0)
  851. self._storefd.truncate()
  852. lxml.etree.ElementTree(self.__xml__()).write(
  853. self._storefd, encoding='utf-8', pretty_print=True)
  854. self._storefd.sync()
  855. os.chmod(self._store, 0660)
  856. os.chown(self._store, -1, grp.getgrnam('qubes').gr_gid)
  857. def save_labels(self):
  858. '''Serialise labels
  859. :rtype: lxml.etree._Element
  860. '''
  861. labels = lxml.etree.Element('labels')
  862. for label in self.labels:
  863. labels.append(label.__xml__())
  864. return labels
  865. def add_new_vm(self, vm):
  866. '''Add new Virtual Machine to colletion
  867. '''
  868. self.domains.add(vm)
  869. @qubes.events.handler('domain-pre-deleted')
  870. def on_domain_pre_deleted(self, event, vm):
  871. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  872. appvms = self.get_vms_based_on(vm)
  873. if appvms:
  874. raise QubesException(
  875. 'Cannot remove template that has dependent AppVMs. '
  876. 'Affected are: {}'.format(', '.join(
  877. vm.name for name in sorted(appvms))))
  878. @qubes.events.handler('domain-deleted')
  879. def on_domain_deleted(self, event, vm):
  880. if self.default_netvm == vm:
  881. del self.default_netvm
  882. if self.default_fw_netvm == vm:
  883. del self.default_fw_netvm
  884. if self.clockvm == vm:
  885. del self.clockvm
  886. if self.updatevm == vm:
  887. del self.updatevm
  888. if self.default_template == vm:
  889. del self.default_template
  890. return super(QubesVmCollection, self).pop(qid)
  891. @qubes.events.handler('property-pre-set:clockvm')
  892. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  893. if 'ntpd' in newvalue.services:
  894. if newvalue.services['ntpd']:
  895. raise QubesException(
  896. 'Cannot set {!r} as {!r} property since it has ntpd enabled.'.format(
  897. newvalue, name))
  898. else:
  899. newvalue.services['ntpd'] = False
  900. @qubes.events.handler('property-pre-set:default_netvm')
  901. def on_property_pre_set_default_netvm(self, event, name, newvalue, oldvalue=None):
  902. if newvalue is not None and oldvalue is not None \
  903. and oldvalue.is_running() and not newvalue.is_running() \
  904. and self.domains.get_vms_connected_to(oldvalue):
  905. raise QubesException(
  906. 'Cannot change default_netvm to domain that is not running ({!r}).'.format(
  907. newvalue))
  908. @qubes.events.handler('property-set:default_fw_netvm')
  909. def on_property_set_default_netvm(self, event, name, newvalue, oldvalue=None):
  910. for vm in self.domains:
  911. if not vm.provides_network and vm.property_is_default('netvm'):
  912. # fire property-del:netvm as it is responsible for resetting
  913. # netvm to it's default value
  914. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  915. @qubes.events.handler('property-set:default_netvm')
  916. def on_property_set_default_netvm(self, event, name, newvalue, oldvalue=None):
  917. for vm in self.domains:
  918. if vm.provides_network and vm.property_is_default('netvm'):
  919. # fire property-del:netvm as it is responsible for resetting
  920. # netvm to it's default value
  921. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  922. # load plugins
  923. import qubes._pluginloader