__init__.py 36 KB

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