app.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. import collections
  26. import errno
  27. import functools
  28. import grp
  29. import logging
  30. import os
  31. import random
  32. import sys
  33. import tempfile
  34. import time
  35. import uuid
  36. import jinja2
  37. import lxml.etree
  38. import libvirt
  39. try:
  40. import xen.lowlevel.xs
  41. import xen.lowlevel.xc
  42. except ImportError:
  43. pass
  44. if os.name == 'posix':
  45. # pylint: disable=wrong-import-order
  46. import fcntl
  47. elif os.name == 'nt':
  48. # pylint: disable=import-error
  49. import win32con
  50. import win32file
  51. import pywintypes
  52. else:
  53. raise RuntimeError("Qubes works only on POSIX or WinNT systems")
  54. import qubes
  55. import qubes.ext
  56. import qubes.utils
  57. import qubes.vm.adminvm
  58. import qubes.vm.qubesvm
  59. import qubes.vm.templatevm
  60. class VirDomainWrapper(object):
  61. # pylint: disable=too-few-public-methods
  62. def __init__(self, connection, vm):
  63. self._connection = connection
  64. self._vm = vm
  65. def _reconnect_if_dead(self):
  66. is_dead = not self._vm.connect().isAlive()
  67. if is_dead:
  68. # pylint: disable=protected-access
  69. self._connection._reconnect_if_dead()
  70. self._vm = self._connection._conn.lookupByUUID(self._vm.getUUID())
  71. return is_dead
  72. def __getattr__(self, attrname):
  73. attr = getattr(self._vm, attrname)
  74. if not isinstance(attr, collections.Callable):
  75. return attr
  76. @functools.wraps(attr)
  77. def wrapper(*args, **kwargs):
  78. try:
  79. return attr(*args, **kwargs)
  80. except libvirt.libvirtError:
  81. if self._reconnect_if_dead():
  82. return getattr(self._vm, attrname)(*args, **kwargs)
  83. raise
  84. return wrapper
  85. class VirConnectWrapper(object):
  86. # pylint: disable=too-few-public-methods
  87. def __init__(self, uri):
  88. self._conn = libvirt.open(uri)
  89. def _reconnect_if_dead(self):
  90. is_dead = not self._conn.isAlive()
  91. if is_dead:
  92. self._conn = libvirt.open(self._conn.getURI())
  93. return is_dead
  94. def _wrap_domain(self, ret):
  95. if isinstance(ret, libvirt.virDomain):
  96. ret = VirDomainWrapper(self, ret)
  97. return ret
  98. def __getattr__(self, attrname):
  99. attr = getattr(self._conn, attrname)
  100. if not isinstance(attr, collections.Callable):
  101. return attr
  102. @functools.wraps(attr)
  103. def wrapper(*args, **kwargs):
  104. try:
  105. return self._wrap_domain(attr(*args, **kwargs))
  106. except libvirt.libvirtError:
  107. if self._reconnect_if_dead():
  108. return self._wrap_domain(
  109. getattr(self._conn, attrname)(*args, **kwargs))
  110. raise
  111. return wrapper
  112. class VMMConnection(object):
  113. '''Connection to Virtual Machine Manager (libvirt)'''
  114. def __init__(self, offline_mode=False):
  115. self._libvirt_conn = None
  116. self._xs = None
  117. self._xc = None
  118. self._offline_mode = offline_mode
  119. @property
  120. def offline_mode(self):
  121. '''Check or enable offline mode (do not actually connect to vmm)'''
  122. return self._offline_mode
  123. def _libvirt_error_handler(self, ctx, error):
  124. pass
  125. def init_vmm_connection(self):
  126. '''Initialise connection
  127. This method is automatically called when getting'''
  128. if self._libvirt_conn is not None:
  129. # Already initialized
  130. return
  131. if self._offline_mode:
  132. # Do not initialize in offline mode
  133. raise qubes.exc.QubesException(
  134. 'VMM operations disabled in offline mode')
  135. if 'xen.lowlevel.xs' in sys.modules:
  136. self._xs = xen.lowlevel.xs.xs()
  137. if 'xen.lowlevel.cs' in sys.modules:
  138. self._xc = xen.lowlevel.xc.xc()
  139. self._libvirt_conn = VirConnectWrapper(
  140. qubes.config.defaults['libvirt_uri'])
  141. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  142. @property
  143. def libvirt_conn(self):
  144. '''Connection to libvirt'''
  145. self.init_vmm_connection()
  146. return self._libvirt_conn
  147. @property
  148. def xs(self):
  149. '''Connection to Xen Store
  150. This property in available only when running on Xen.
  151. '''
  152. # XXX what about the case when we run under KVM,
  153. # but xen modules are importable?
  154. if 'xen.lowlevel.xs' not in sys.modules:
  155. raise AttributeError(
  156. 'xs object is available under Xen hypervisor only')
  157. self.init_vmm_connection()
  158. return self._xs
  159. @property
  160. def xc(self):
  161. '''Connection to Xen
  162. This property in available only when running on Xen.
  163. '''
  164. # XXX what about the case when we run under KVM,
  165. # but xen modules are importable?
  166. if 'xen.lowlevel.xc' not in sys.modules:
  167. raise AttributeError(
  168. 'xc object is available under Xen hypervisor only')
  169. self.init_vmm_connection()
  170. return self._xs
  171. def __del__(self):
  172. if self._libvirt_conn:
  173. self._libvirt_conn.close()
  174. class QubesHost(object):
  175. '''Basic information about host machine
  176. :param qubes.Qubes app: Qubes application context (must have \
  177. :py:attr:`Qubes.vmm` attribute defined)
  178. '''
  179. def __init__(self, app):
  180. self.app = app
  181. self._no_cpus = None
  182. self._total_mem = None
  183. self._physinfo = None
  184. def _fetch(self):
  185. if self._no_cpus is not None:
  186. return
  187. # pylint: disable=unused-variable
  188. (model, memory, cpus, mhz, nodes, socket, cores, threads) = \
  189. self.app.vmm.libvirt_conn.getInfo()
  190. self._total_mem = long(memory) * 1024
  191. self._no_cpus = cpus
  192. self.app.log.debug('QubesHost: no_cpus={} memory_total={}'.format(
  193. self.no_cpus, self.memory_total))
  194. try:
  195. self.app.log.debug('QubesHost: xen_free_memory={}'.format(
  196. self.get_free_xen_memory()))
  197. except NotImplementedError:
  198. pass
  199. @property
  200. def memory_total(self):
  201. '''Total memory, in kbytes'''
  202. self._fetch()
  203. return self._total_mem
  204. @property
  205. def no_cpus(self):
  206. '''Number of CPUs'''
  207. self._fetch()
  208. return self._no_cpus
  209. def get_free_xen_memory(self):
  210. '''Get free memory from Xen's physinfo.
  211. :raises NotImplementedError: when not under Xen
  212. '''
  213. try:
  214. self._physinfo = self.app.xc.physinfo()
  215. except AttributeError:
  216. raise NotImplementedError('This function requires Xen hypervisor')
  217. return long(self._physinfo['free_memory'])
  218. def measure_cpu_usage(self, previous_time=None, previous=None,
  219. wait_time=1):
  220. '''Measure cpu usage for all domains at once.
  221. This function requires Xen hypervisor.
  222. .. versionchanged:: 3.0
  223. argument order to match return tuple
  224. :raises NotImplementedError: when not under Xen
  225. '''
  226. if previous is None:
  227. previous_time = time.time()
  228. previous = {}
  229. try:
  230. info = self.app.vmm.xc.domain_getinfo(0, qubes.config.max_qid)
  231. except AttributeError:
  232. raise NotImplementedError(
  233. 'This function requires Xen hypervisor')
  234. for vm in info:
  235. previous[vm['domid']] = {}
  236. previous[vm['domid']]['cpu_time'] = (
  237. vm['cpu_time'] / vm['online_vcpus'])
  238. previous[vm['domid']]['cpu_usage'] = 0
  239. time.sleep(wait_time)
  240. current_time = time.time()
  241. current = {}
  242. try:
  243. info = self.app.vmm.xc.domain_getinfo(0, qubes.config.max_qid)
  244. except AttributeError:
  245. raise NotImplementedError(
  246. 'This function requires Xen hypervisor')
  247. for vm in info:
  248. current[vm['domid']] = {}
  249. current[vm['domid']]['cpu_time'] = (
  250. vm['cpu_time'] / max(vm['online_vcpus'], 1))
  251. if vm['domid'] in previous.keys():
  252. current[vm['domid']]['cpu_usage'] = (
  253. float(current[vm['domid']]['cpu_time'] -
  254. previous[vm['domid']]['cpu_time']) /
  255. long(1000 ** 3) / (current_time - previous_time) * 100)
  256. if current[vm['domid']]['cpu_usage'] < 0:
  257. # VM has been rebooted
  258. current[vm['domid']]['cpu_usage'] = 0
  259. else:
  260. current[vm['domid']]['cpu_usage'] = 0
  261. return (current_time, current)
  262. class VMCollection(object):
  263. '''A collection of Qubes VMs
  264. VMCollection supports ``in`` operator. You may test for ``qid``, ``name``
  265. and whole VM object's presence.
  266. Iterating over VMCollection will yield machine objects.
  267. '''
  268. def __init__(self, app):
  269. self.app = app
  270. self._dict = dict()
  271. def __repr__(self):
  272. return '<{} {!r}>'.format(
  273. self.__class__.__name__, list(sorted(self.keys())))
  274. def items(self):
  275. '''Iterate over ``(qid, vm)`` pairs'''
  276. for qid in self.qids():
  277. yield (qid, self[qid])
  278. def qids(self):
  279. '''Iterate over all qids
  280. qids are sorted by numerical order.
  281. '''
  282. return iter(sorted(self._dict.keys()))
  283. keys = qids
  284. def names(self):
  285. '''Iterate over all names
  286. names are sorted by lexical order.
  287. '''
  288. return iter(sorted(vm.name for vm in self._dict.values()))
  289. def vms(self):
  290. '''Iterate over all machines
  291. vms are sorted by qid.
  292. '''
  293. return iter(sorted(self._dict.values()))
  294. __iter__ = vms
  295. values = vms
  296. def add(self, value, _enable_events=True):
  297. '''Add VM to collection
  298. :param qubes.vm.BaseVM value: VM to add
  299. :raises TypeError: when value is of wrong type
  300. :raises ValueError: when there is already VM which has equal ``qid``
  301. '''
  302. # this violates duck typing, but is needed
  303. # for VMProperty to function correctly
  304. if not isinstance(value, qubes.vm.BaseVM):
  305. raise TypeError('{} holds only BaseVM instances'.format(
  306. self.__class__.__name__))
  307. if value.qid in self:
  308. raise ValueError('This collection already holds VM that has '
  309. 'qid={!r} ({!r})'.format(value.qid, self[value.qid]))
  310. if value.name in self:
  311. raise ValueError('This collection already holds VM that has '
  312. 'name={!r} ({!r})'.format(value.name, self[value.name]))
  313. self._dict[value.qid] = value
  314. if _enable_events:
  315. value.events_enabled = True
  316. self.app.fire_event('domain-add', value)
  317. return value
  318. def __getitem__(self, key):
  319. if isinstance(key, int):
  320. return self._dict[key]
  321. if isinstance(key, basestring):
  322. for vm in self:
  323. if vm.name == key:
  324. return vm
  325. raise KeyError(key)
  326. if isinstance(key, qubes.vm.BaseVM):
  327. key = key.uuid
  328. if isinstance(key, uuid.UUID):
  329. for vm in self:
  330. if vm.uuid == key:
  331. return vm
  332. raise KeyError(key)
  333. raise KeyError(key)
  334. def __delitem__(self, key):
  335. vm = self[key]
  336. self.app.fire_event_pre('domain-pre-delete', vm)
  337. del self._dict[vm.qid]
  338. self.app.fire_event('domain-delete', vm)
  339. def __contains__(self, key):
  340. return any((key == vm or key == vm.qid or key == vm.name)
  341. for vm in self)
  342. def __len__(self):
  343. return len(self._dict)
  344. def get_vms_based_on(self, template):
  345. template = self[template]
  346. return set(vm for vm in self
  347. if hasattr(vm, 'template') and vm.template == template)
  348. def get_vms_connected_to(self, netvm):
  349. new_vms = set([self[netvm]])
  350. dependent_vms = set()
  351. # Dependency resolving only makes sense on NetVM (or derivative)
  352. # if not self[netvm_qid].is_netvm():
  353. # return set([])
  354. while len(new_vms) > 0:
  355. cur_vm = new_vms.pop()
  356. for vm in cur_vm.connected_vms:
  357. if vm in dependent_vms:
  358. continue
  359. dependent_vms.add(vm.qid)
  360. # if vm.is_netvm():
  361. new_vms.add(vm.qid)
  362. return dependent_vms
  363. # XXX with Qubes Admin Api this will probably lead to race condition
  364. # whole process of creating and adding should be synchronised
  365. def get_new_unused_qid(self):
  366. used_ids = set(self.qids())
  367. for i in range(1, qubes.config.max_qid):
  368. if i not in used_ids:
  369. return i
  370. raise LookupError("Cannot find unused qid!")
  371. def get_new_unused_netid(self):
  372. used_ids = set([vm.netid for vm in self]) # if vm.is_netvm()])
  373. for i in range(1, qubes.config.max_netid):
  374. if i not in used_ids:
  375. return i
  376. raise LookupError("Cannot find unused netid!")
  377. def get_new_unused_dispid(self):
  378. for _ in range(qubes.config.max_dispid ** 0.5):
  379. dispid = random.SystemRandom().randrange(qubes.config.max_dispid)
  380. if not any(getattr(vm, 'dispid', None) == dispid for vm in self):
  381. return dispid
  382. raise LookupError((
  383. 'https://xkcd.com/221/',
  384. 'http://dilbert.com/strip/2001-10-25')[random.randint(0, 1)])
  385. class Qubes(qubes.PropertyHolder):
  386. '''Main Qubes application
  387. :param str store: path to ``qubes.xml``
  388. The store is loaded in stages:
  389. 1. In the first stage there are loaded some basic features from store
  390. (currently labels).
  391. 2. In the second stage stubs for all VMs are loaded. They are filled
  392. with their basic properties, like ``qid`` and ``name``.
  393. 3. In the third stage all global properties are loaded. They often
  394. reference VMs, like default netvm, so they should be filled after
  395. loading VMs.
  396. 4. In the fourth stage all remaining VM properties are loaded. They
  397. also need all VMs loaded, because they represent dependencies
  398. between VMs like aforementioned netvm.
  399. 5. In the fifth stage there are some fixups to ensure sane system
  400. operation.
  401. This class emits following events:
  402. .. event:: domain-add (subject, event, vm)
  403. When domain is added.
  404. :param subject: Event emitter
  405. :param event: Event name (``'domain-add'``)
  406. :param vm: Domain object
  407. .. event:: domain-delete (subject, event, vm)
  408. When domain is deleted. VM still has reference to ``app`` object,
  409. but is not contained within VMCollection.
  410. :param subject: Event emitter
  411. :param event: Event name (``'domain-delete'``)
  412. :param vm: Domain object
  413. Methods and attributes:
  414. '''
  415. default_netvm = qubes.VMProperty('default_netvm', load_stage=3,
  416. default=None, allow_none=True,
  417. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  418. that AppVMs are not connected to the Internet.''')
  419. default_fw_netvm = qubes.VMProperty('default_fw_netvm', load_stage=3,
  420. default=None, allow_none=True,
  421. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  422. that ProxyVMs (including FirewallVM) are not connected to the
  423. Internet.''')
  424. default_template = qubes.VMProperty('default_template', load_stage=3,
  425. vmclass=qubes.vm.templatevm.TemplateVM,
  426. doc='Default template for new AppVMs')
  427. updatevm = qubes.VMProperty('updatevm', load_stage=3,
  428. allow_none=True,
  429. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  430. TemplateVMs''')
  431. clockvm = qubes.VMProperty('clockvm', load_stage=3,
  432. allow_none=True,
  433. doc='Which VM to use as NTP proxy for updating AdminVM')
  434. default_kernel = qubes.property('default_kernel', load_stage=3,
  435. doc='Which kernel to use when not overriden in VM')
  436. # TODO #1637 #892
  437. check_updates_vm = qubes.property('check_updates_vm',
  438. type=bool, setter=qubes.property.bool,
  439. default=True,
  440. doc='check for updates inside qubes')
  441. def __init__(self, store=None, load=True, offline_mode=False, **kwargs):
  442. #: logger instance for logging global messages
  443. self.log = logging.getLogger('app')
  444. self._extensions = qubes.ext.get_extensions()
  445. #: collection of all VMs managed by this Qubes instance
  446. self.domains = VMCollection(self)
  447. #: collection of all available labels for VMs
  448. self.labels = {}
  449. #: collection of all pools
  450. self.pools = {}
  451. #: Connection to VMM
  452. self.vmm = VMMConnection(offline_mode=offline_mode)
  453. #: Information about host system
  454. self.host = QubesHost(self)
  455. if store is not None:
  456. self._store = store
  457. else:
  458. self._store = os.environ.get('QUBES_XML_PATH',
  459. os.path.join(
  460. qubes.config.system_path['qubes_base_dir'],
  461. qubes.config.system_path['qubes_store_filename']))
  462. super(Qubes, self).__init__(xml=None, **kwargs)
  463. self.__load_timestamp = None
  464. #: jinja2 environment for libvirt XML templates
  465. self.env = jinja2.Environment(
  466. loader=jinja2.FileSystemLoader('/usr/share/qubes/templates'),
  467. undefined=jinja2.StrictUndefined)
  468. if load:
  469. self.load()
  470. self.events_enabled = True
  471. @property
  472. def store(self):
  473. return self._store
  474. def load(self):
  475. '''Open qubes.xml
  476. :throws EnvironmentError: failure on parsing store
  477. :throws xml.parsers.expat.ExpatError: failure on parsing store
  478. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  479. '''
  480. try:
  481. fd = os.open(self._store, os.O_RDWR) # no O_CREAT
  482. except OSError as e:
  483. if e.errno != errno.ENOENT:
  484. raise
  485. raise qubes.exc.QubesException(
  486. 'Qubes XML store {!r} is missing; use qubes-create tool'.format(
  487. self._store))
  488. fh = os.fdopen(fd, 'rb')
  489. if os.name == 'posix':
  490. fcntl.lockf(fh, fcntl.LOCK_EX)
  491. elif os.name == 'nt':
  492. # pylint: disable=protected-access
  493. win32file.LockFileEx(
  494. win32file._get_osfhandle(fh.fileno()),
  495. win32con.LOCKFILE_EXCLUSIVE_LOCK,
  496. 0, -0x10000,
  497. pywintypes.OVERLAPPED())
  498. self.xml = lxml.etree.parse(fh)
  499. # stage 1: load labels and pools
  500. for node in self.xml.xpath('./labels/label'):
  501. label = qubes.Label.fromxml(node)
  502. self.labels[label.index] = label
  503. for node in self.xml.xpath('./pools/pool'):
  504. name = node.get('name')
  505. assert name, "Pool name '%s' is invalid " % name
  506. try:
  507. self.pools[name] = self._get_pool(**node.attrib)
  508. except qubes.exc.QubesException as e:
  509. self.log.error(e.message)
  510. # stage 2: load VMs
  511. for node in self.xml.xpath('./domains/domain'):
  512. # pylint: disable=no-member
  513. cls = self.get_vm_class(node.get('class'))
  514. vm = cls(self, node)
  515. vm.load_properties(load_stage=2)
  516. vm.init_log()
  517. self.domains.add(vm, _enable_events=False)
  518. if 0 not in self.domains:
  519. self.domains.add(
  520. qubes.vm.adminvm.AdminVM(self, None, qid=0, name='dom0'),
  521. _enable_events=False)
  522. # stage 3: load global properties
  523. self.load_properties(load_stage=3)
  524. # stage 4: fill all remaining VM properties
  525. for vm in self.domains:
  526. vm.load_properties(load_stage=4)
  527. # stage 5: misc fixups
  528. self.property_require('default_fw_netvm', allow_none=True)
  529. self.property_require('default_netvm', allow_none=True)
  530. self.property_require('default_template')
  531. self.property_require('clockvm', allow_none=True)
  532. self.property_require('updatevm', allow_none=True)
  533. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  534. # using 123/udp port)
  535. if hasattr(self, 'clockvm') and self.clockvm is not None:
  536. if self.clockvm.features.get('services/ntpd', False):
  537. self.log.warning(
  538. 'VM set as clockvm (%r) has enabled \'ntpd\' service! '
  539. 'Expect failure when syncing time in dom0.',
  540. self.clockvm)
  541. else:
  542. self.clockvm.features['services/ntpd'] = ''
  543. for vm in self.domains:
  544. vm.events_enabled = True
  545. vm.fire_event('domain-load')
  546. # get a file timestamp (before closing it - still holding the lock!),
  547. # to detect whether anyone else have modified it in the meantime
  548. self.__load_timestamp = os.path.getmtime(self._store)
  549. # intentionally do not call explicit unlock
  550. fh.close()
  551. del fh
  552. def __xml__(self):
  553. element = lxml.etree.Element('qubes')
  554. element.append(self.xml_labels())
  555. pools_xml = lxml.etree.Element('pools')
  556. for pool in self.pools.values():
  557. xml = pool.__xml__()
  558. if xml is not None:
  559. pools_xml.append(xml)
  560. element.append(pools_xml)
  561. element.append(self.xml_properties())
  562. domains = lxml.etree.Element('domains')
  563. for vm in self.domains:
  564. domains.append(vm.__xml__())
  565. element.append(domains)
  566. return element
  567. def save(self):
  568. '''Save all data to qubes.xml
  569. There are several problems with saving :file:`qubes.xml` which must be
  570. mitigated:
  571. - Running out of disk space. No space left should not result in empty
  572. file. This is done by writing to temporary file and then renaming.
  573. - Attempts to write two or more files concurrently. This is done by
  574. sophisticated locking.
  575. :throws EnvironmentError: failure on saving
  576. '''
  577. while True:
  578. fd_old = os.open(self._store, os.O_RDWR | os.O_CREAT)
  579. if os.name == 'posix':
  580. fcntl.lockf(fd_old, fcntl.LOCK_EX)
  581. elif os.name == 'nt':
  582. # pylint: disable=protected-access
  583. overlapped = pywintypes.OVERLAPPED()
  584. win32file.LockFileEx(
  585. win32file._get_osfhandle(fd_old),
  586. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  587. # While we were waiting for lock, someone could have unlink()ed (or
  588. # rename()d) our file out of the filesystem. We have to ensure we
  589. # got lock on something linked to filesystem. If not, try again.
  590. if os.fstat(fd_old) == os.stat(self._store):
  591. break
  592. else:
  593. os.close(fd_old)
  594. if self.__load_timestamp:
  595. current_file_timestamp = os.path.getmtime(self._store)
  596. if current_file_timestamp != self.__load_timestamp:
  597. os.close(fd_old)
  598. raise qubes.exc.QubesException(
  599. "Someone else modified qubes.xml in the meantime")
  600. fh_new = tempfile.NamedTemporaryFile(prefix=self._store, delete=False)
  601. lxml.etree.ElementTree(self.__xml__()).write(
  602. fh_new, encoding='utf-8', pretty_print=True)
  603. fh_new.flush()
  604. os.chmod(fh_new.name, 0660)
  605. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  606. os.rename(fh_new.name, self._store)
  607. # intentionally do not call explicit unlock to not unlock the file
  608. # before all buffers are flushed
  609. fh_new.close()
  610. # update stored mtime, in case of multiple save() calls without
  611. # loading qubes.xml again
  612. self.__load_timestamp = os.path.getmtime(self._store)
  613. os.close(fd_old)
  614. def load_initial_values(self):
  615. self.labels = {
  616. 1: qubes.Label(1, '0xcc0000', 'red'),
  617. 2: qubes.Label(2, '0xf57900', 'orange'),
  618. 3: qubes.Label(3, '0xedd400', 'yellow'),
  619. 4: qubes.Label(4, '0x73d216', 'green'),
  620. 5: qubes.Label(5, '0x555753', 'gray'),
  621. 6: qubes.Label(6, '0x3465a4', 'blue'),
  622. 7: qubes.Label(7, '0x75507b', 'purple'),
  623. 8: qubes.Label(8, '0x000000', 'black'),
  624. }
  625. for name, config in qubes.config.defaults['pool_configs'].items():
  626. self.pools[name] = self._get_pool(**config)
  627. self.domains.add(
  628. qubes.vm.adminvm.AdminVM(self, None, qid=0, name='dom0'))
  629. @classmethod
  630. def create_empty_store(cls, *args, **kwargs):
  631. self = cls(*args, load=False, **kwargs)
  632. self.load_initial_values()
  633. self.save()
  634. return self
  635. def xml_labels(self):
  636. '''Serialise labels
  637. :rtype: lxml.etree._Element
  638. '''
  639. labels = lxml.etree.Element('labels')
  640. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  641. labels.append(label.__xml__())
  642. return labels
  643. @staticmethod
  644. def get_vm_class(clsname):
  645. '''Find the class for a domain.
  646. Classess are registered as setuptools' entry points in ``qubes.vm``
  647. group. Any package may supply their own classess.
  648. :param str clsname: name of the class
  649. :return type: class
  650. '''
  651. try:
  652. return qubes.utils.get_entry_point_one('qubes.vm', clsname)
  653. except KeyError:
  654. raise qubes.exc.QubesException(
  655. 'no such VM class: {!r}'.format(clsname))
  656. # don't catch TypeError
  657. def add_new_vm(self, cls, qid=None, **kwargs):
  658. '''Add new Virtual Machine to colletion
  659. '''
  660. if qid is None:
  661. qid = self.domains.get_new_unused_qid()
  662. # handle default template; specifically allow template=None (do not
  663. # override it with default template)
  664. if 'template' not in kwargs and hasattr(cls, 'template'):
  665. kwargs['template'] = self.default_template
  666. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  667. def get_label(self, label):
  668. '''Get label as identified by index or name
  669. :throws KeyError: when label is not found
  670. '''
  671. # first search for index, verbatim
  672. try:
  673. return self.labels[label]
  674. except KeyError:
  675. pass
  676. # then search for name
  677. for i in self.labels.values():
  678. if i.name == label:
  679. return i
  680. # last call, if label is a number represented as str, search in indices
  681. try:
  682. return self.labels[int(label)]
  683. except (KeyError, ValueError):
  684. pass
  685. raise KeyError(label)
  686. def add_pool(self, name, **kwargs):
  687. """ Add a storage pool to config."""
  688. if name in self.pools.keys():
  689. raise qubes.exc.QubesException('pool named %s already exists \n' %
  690. name)
  691. kwargs['name'] = name
  692. pool = self._get_pool(**kwargs)
  693. pool.setup()
  694. self.pools[name] = pool
  695. def remove_pool(self, name):
  696. """ Remove a storage pool from config file. """
  697. try:
  698. pool = self.pools[name]
  699. del self.pools[name]
  700. pool.destroy()
  701. except KeyError:
  702. return
  703. def get_pool(self, name):
  704. ''' Returns a :py:class:`qubes.storage.Pool` instance '''
  705. try:
  706. return self.pools[name]
  707. except KeyError:
  708. raise qubes.exc.QubesException('Unknown storage pool ' + name)
  709. @staticmethod
  710. def _get_pool(**kwargs):
  711. try:
  712. name = kwargs['name']
  713. assert name, 'Name needs to be an non empty string'
  714. except KeyError:
  715. raise qubes.exc.QubesException('No pool name for pool')
  716. try:
  717. driver = kwargs['driver']
  718. except KeyError:
  719. raise qubes.exc.QubesException('No driver specified for pool ' +
  720. name)
  721. try:
  722. klass = qubes.utils.get_entry_point_one(
  723. qubes.storage.STORAGE_ENTRY_POINT, driver)
  724. del kwargs['driver']
  725. return klass(**kwargs)
  726. except KeyError:
  727. raise qubes.exc.QubesException('No driver %s for pool %s' %
  728. (driver, name))
  729. @qubes.events.handler('domain-pre-delete')
  730. def on_domain_pre_deleted(self, event, vm):
  731. # pylint: disable=unused-argument
  732. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  733. appvms = self.domains.get_vms_based_on(vm)
  734. if appvms:
  735. raise qubes.exc.QubesException(
  736. 'Cannot remove template that has dependent AppVMs. '
  737. 'Affected are: {}'.format(', '.join(
  738. vm.name for name in sorted(appvms))))
  739. @qubes.events.handler('domain-delete')
  740. def on_domain_deleted(self, event, vm):
  741. # pylint: disable=unused-argument
  742. for propname in (
  743. 'default_netvm',
  744. 'default_fw_netvm',
  745. 'clockvm',
  746. 'updatevm',
  747. 'default_template',
  748. ):
  749. try:
  750. if getattr(self, propname) == vm:
  751. delattr(self, propname)
  752. except AttributeError:
  753. pass
  754. @qubes.events.handler('property-pre-set:clockvm')
  755. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  756. # pylint: disable=unused-argument,no-self-use
  757. if newvalue is None:
  758. return
  759. if newvalue.features.get('services/ntpd', False):
  760. raise qubes.exc.QubesVMError(newvalue,
  761. 'Cannot set {!r} as {!r} since it has ntpd enabled.'.format(
  762. newvalue.name, name))
  763. else:
  764. newvalue.features['services/ntpd'] = ''
  765. @qubes.events.handler(
  766. 'property-pre-set:default_netvm',
  767. 'property-pre-set:default_fw_netvm')
  768. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  769. oldvalue=None):
  770. # pylint: disable=unused-argument,invalid-name
  771. if newvalue is not None and oldvalue is not None \
  772. and oldvalue.is_running() and not newvalue.is_running() \
  773. and self.domains.get_vms_connected_to(oldvalue):
  774. raise qubes.exc.QubesVMNotRunningError(newvalue,
  775. 'Cannot change {!r} to domain that '
  776. 'is not running ({!r}).'.format(name, newvalue.name))
  777. @qubes.events.handler('property-set:default_fw_netvm')
  778. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  779. oldvalue=None):
  780. # pylint: disable=unused-argument,invalid-name
  781. for vm in self.domains:
  782. if not vm.provides_network and vm.property_is_default('netvm'):
  783. # fire property-del:netvm as it is responsible for resetting
  784. # netvm to it's default value
  785. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  786. @qubes.events.handler('property-set:default_netvm')
  787. def on_property_set_default_netvm(self, event, name, newvalue,
  788. oldvalue=None):
  789. # pylint: disable=unused-argument
  790. for vm in self.domains:
  791. if vm.provides_network and vm.property_is_default('netvm'):
  792. # fire property-del:netvm as it is responsible for resetting
  793. # netvm to it's default value
  794. vm.fire_event('property-del:netvm', 'netvm', oldvalue)