__init__.py 32 KB

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