app.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. import collections
  24. import errno
  25. import functools
  26. import grp
  27. import logging
  28. import os
  29. import random
  30. import subprocess
  31. import sys
  32. import tempfile
  33. import time
  34. import traceback
  35. import uuid
  36. import lxml.etree
  37. import jinja2
  38. import libvirt
  39. try:
  40. import xen.lowlevel.xs # pylint: disable=wrong-import-order
  41. import xen.lowlevel.xc # pylint: disable=wrong-import-order
  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. # pylint: disable=wrong-import-position
  55. import qubes
  56. import qubes.ext
  57. import qubes.utils
  58. import qubes.storage
  59. import qubes.vm
  60. import qubes.vm.adminvm
  61. import qubes.vm.qubesvm
  62. import qubes.vm.templatevm
  63. # pylint: enable=wrong-import-position
  64. class VirDomainWrapper(object):
  65. # pylint: disable=too-few-public-methods
  66. def __init__(self, connection, vm):
  67. self._connection = connection
  68. self._vm = vm
  69. def _reconnect_if_dead(self):
  70. is_dead = not self._vm.connect().isAlive()
  71. if is_dead:
  72. # pylint: disable=protected-access
  73. self._connection._reconnect_if_dead()
  74. self._vm = self._connection._conn.lookupByUUID(self._vm.UUID())
  75. return is_dead
  76. def __getattr__(self, attrname):
  77. attr = getattr(self._vm, attrname)
  78. if not isinstance(attr, collections.Callable):
  79. return attr
  80. @functools.wraps(attr)
  81. def wrapper(*args, **kwargs):
  82. try:
  83. return attr(*args, **kwargs)
  84. except libvirt.libvirtError:
  85. if self._reconnect_if_dead():
  86. return getattr(self._vm, attrname)(*args, **kwargs)
  87. raise
  88. return wrapper
  89. class VirConnectWrapper(object):
  90. # pylint: disable=too-few-public-methods
  91. def __init__(self, uri):
  92. self._conn = libvirt.open(uri)
  93. def _reconnect_if_dead(self):
  94. is_dead = not self._conn.isAlive()
  95. if is_dead:
  96. self._conn = libvirt.open(self._conn.getURI())
  97. # TODO: re-register event handlers
  98. return is_dead
  99. def _wrap_domain(self, ret):
  100. if isinstance(ret, libvirt.virDomain):
  101. ret = VirDomainWrapper(self, ret)
  102. return ret
  103. def __getattr__(self, attrname):
  104. attr = getattr(self._conn, attrname)
  105. if not isinstance(attr, collections.Callable):
  106. return attr
  107. if attrname == 'close':
  108. return attr
  109. @functools.wraps(attr)
  110. def wrapper(*args, **kwargs):
  111. try:
  112. return self._wrap_domain(attr(*args, **kwargs))
  113. except libvirt.libvirtError:
  114. if self._reconnect_if_dead():
  115. return self._wrap_domain(
  116. getattr(self._conn, attrname)(*args, **kwargs))
  117. raise
  118. return wrapper
  119. class VMMConnection(object):
  120. '''Connection to Virtual Machine Manager (libvirt)'''
  121. def __init__(self, offline_mode=None):
  122. '''
  123. :param offline_mode: enable/disable offline mode; default is to
  124. enable when running in chroot as root, otherwise disable
  125. '''
  126. if offline_mode is None:
  127. offline_mode = bool(os.getuid() == 0 and
  128. os.stat('/') != os.stat('/proc/1/root/.'))
  129. self._offline_mode = offline_mode
  130. self._libvirt_conn = None
  131. self._xs = None
  132. self._xc = None
  133. @property
  134. def offline_mode(self):
  135. '''Check or enable offline mode (do not actually connect to vmm)'''
  136. return self._offline_mode
  137. def _libvirt_error_handler(self, ctx, error):
  138. pass
  139. def init_vmm_connection(self):
  140. '''Initialise connection
  141. This method is automatically called when getting'''
  142. if self._libvirt_conn is not None:
  143. # Already initialized
  144. return
  145. if self._offline_mode:
  146. # Do not initialize in offline mode
  147. raise qubes.exc.QubesException(
  148. 'VMM operations disabled in offline mode')
  149. if 'xen.lowlevel.xs' in sys.modules:
  150. self._xs = xen.lowlevel.xs.xs()
  151. if 'xen.lowlevel.xc' in sys.modules:
  152. self._xc = xen.lowlevel.xc.xc()
  153. self._libvirt_conn = VirConnectWrapper(
  154. qubes.config.defaults['libvirt_uri'])
  155. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  156. @property
  157. def libvirt_conn(self):
  158. '''Connection to libvirt'''
  159. self.init_vmm_connection()
  160. return self._libvirt_conn
  161. @property
  162. def xs(self):
  163. '''Connection to Xen Store
  164. This property in available only when running on Xen.
  165. '''
  166. # XXX what about the case when we run under KVM,
  167. # but xen modules are importable?
  168. if 'xen.lowlevel.xs' not in sys.modules:
  169. raise AttributeError(
  170. 'xs object is available under Xen hypervisor only')
  171. self.init_vmm_connection()
  172. return self._xs
  173. @property
  174. def xc(self):
  175. '''Connection to Xen
  176. This property in available only when running on Xen.
  177. '''
  178. # XXX what about the case when we run under KVM,
  179. # but xen modules are importable?
  180. if 'xen.lowlevel.xc' not in sys.modules:
  181. raise AttributeError(
  182. 'xc object is available under Xen hypervisor only')
  183. self.init_vmm_connection()
  184. return self._xc
  185. def close(self):
  186. libvirt.registerErrorHandler(None, None)
  187. if self._xs:
  188. self._xs.close()
  189. self._xs = None
  190. if self._libvirt_conn:
  191. self._libvirt_conn.close()
  192. self._libvirt_conn = None
  193. self._xc = None # and pray it will get garbage-collected
  194. class QubesHost(object):
  195. '''Basic information about host machine
  196. :param qubes.Qubes app: Qubes application context (must have \
  197. :py:attr:`Qubes.vmm` attribute defined)
  198. '''
  199. def __init__(self, app):
  200. self.app = app
  201. self._no_cpus = None
  202. self._total_mem = None
  203. self._physinfo = None
  204. def _fetch(self):
  205. if self._no_cpus is not None:
  206. return
  207. # pylint: disable=unused-variable
  208. (model, memory, cpus, mhz, nodes, socket, cores, threads) = \
  209. self.app.vmm.libvirt_conn.getInfo()
  210. self._total_mem = int(memory) * 1024
  211. self._no_cpus = cpus
  212. self.app.log.debug('QubesHost: no_cpus={} memory_total={}'.format(
  213. self.no_cpus, self.memory_total))
  214. try:
  215. self.app.log.debug('QubesHost: xen_free_memory={}'.format(
  216. self.get_free_xen_memory()))
  217. except NotImplementedError:
  218. pass
  219. @property
  220. def memory_total(self):
  221. '''Total memory, in kbytes'''
  222. if self.app.vmm.offline_mode:
  223. return 2**64-1
  224. self._fetch()
  225. return self._total_mem
  226. @property
  227. def no_cpus(self):
  228. '''Number of CPUs'''
  229. if self.app.vmm.offline_mode:
  230. return 42
  231. self._fetch()
  232. return self._no_cpus
  233. def get_free_xen_memory(self):
  234. '''Get free memory from Xen's physinfo.
  235. :raises NotImplementedError: when not under Xen
  236. '''
  237. try:
  238. self._physinfo = self.app.xc.physinfo()
  239. except AttributeError:
  240. raise NotImplementedError('This function requires Xen hypervisor')
  241. return int(self._physinfo['free_memory'])
  242. def get_vm_stats(self, previous_time=None, previous=None, only_vm=None):
  243. '''Measure cpu usage for all domains at once.
  244. If previous measurements are given, CPU usage will be given in
  245. percents of time. Otherwise only absolute value (seconds).
  246. Return a tuple of (measurements_time, measurements),
  247. where measurements is a dictionary with key: domid, value: dict:
  248. - cpu_time - absolute CPU usage (seconds since its startup)
  249. - cpu_usage - CPU usage in %
  250. - memory_kb - current memory assigned, in kb
  251. This function requires Xen hypervisor.
  252. ..warning:
  253. This function may return info about implementation-specific VMs,
  254. like stubdomains for HVM
  255. :param previous: previous measurement
  256. :param previous_time: time of previous measurement
  257. :param only_vm: get measurements only for this VM
  258. :raises NotImplementedError: when not under Xen
  259. '''
  260. if (previous_time is None) != (previous is None):
  261. raise ValueError(
  262. 'previous and previous_time must be given together (or none)')
  263. if previous is None:
  264. previous = {}
  265. current_time = time.time()
  266. current = {}
  267. try:
  268. if only_vm:
  269. xid = only_vm.xid
  270. if xid < 0:
  271. raise qubes.exc.QubesVMNotRunningError(only_vm)
  272. info = self.app.vmm.xc.domain_getinfo(xid, 1)
  273. if info[0]['domid'] != xid:
  274. raise qubes.exc.QubesVMNotRunningError(only_vm)
  275. else:
  276. info = self.app.vmm.xc.domain_getinfo(0, 1024)
  277. except AttributeError:
  278. raise NotImplementedError(
  279. 'This function requires Xen hypervisor')
  280. # TODO: add stubdomain stats to actual VMs
  281. for vm in info:
  282. domid = vm['domid']
  283. current[domid] = {}
  284. current[domid]['memory_kb'] = vm['mem_kb']
  285. current[domid]['cpu_time'] = int(
  286. vm['cpu_time'] / max(vm['online_vcpus'], 1))
  287. if domid in previous:
  288. current[domid]['cpu_usage'] = int(
  289. (current[domid]['cpu_time'] - previous[domid]['cpu_time'])
  290. / 1000 ** 3 * 100 / (current_time - previous_time))
  291. if current[domid]['cpu_usage'] < 0:
  292. # VM has been rebooted
  293. current[domid]['cpu_usage'] = 0
  294. else:
  295. current[domid]['cpu_usage'] = 0
  296. return (current_time, current)
  297. class VMCollection(object):
  298. '''A collection of Qubes VMs
  299. VMCollection supports ``in`` operator. You may test for ``qid``, ``name``
  300. and whole VM object's presence.
  301. Iterating over VMCollection will yield machine objects.
  302. '''
  303. def __init__(self, app):
  304. self.app = app
  305. self._dict = dict()
  306. def close(self):
  307. del self.app
  308. self._dict.clear()
  309. del self._dict
  310. def __repr__(self):
  311. return '<{} {!r}>'.format(
  312. self.__class__.__name__, list(sorted(self.keys())))
  313. def items(self):
  314. '''Iterate over ``(qid, vm)`` pairs'''
  315. for qid in self.qids():
  316. yield (qid, self[qid])
  317. def qids(self):
  318. '''Iterate over all qids
  319. qids are sorted by numerical order.
  320. '''
  321. return iter(sorted(self._dict.keys()))
  322. keys = qids
  323. def names(self):
  324. '''Iterate over all names
  325. names are sorted by lexical order.
  326. '''
  327. return iter(sorted(vm.name for vm in self._dict.values()))
  328. def vms(self):
  329. '''Iterate over all machines
  330. vms are sorted by qid.
  331. '''
  332. return iter(sorted(self._dict.values()))
  333. __iter__ = vms
  334. values = vms
  335. def add(self, value, _enable_events=True):
  336. '''Add VM to collection
  337. :param qubes.vm.BaseVM value: VM to add
  338. :raises TypeError: when value is of wrong type
  339. :raises ValueError: when there is already VM which has equal ``qid``
  340. '''
  341. # this violates duck typing, but is needed
  342. # for VMProperty to function correctly
  343. if not isinstance(value, qubes.vm.BaseVM):
  344. raise TypeError('{} holds only BaseVM instances'.format(
  345. self.__class__.__name__))
  346. if value.qid in self:
  347. raise ValueError('This collection already holds VM that has '
  348. 'qid={!r} ({!r})'.format(value.qid, self[value.qid]))
  349. if value.name in self:
  350. raise ValueError('A VM named {!s} already exists'
  351. .format(value.name))
  352. self._dict[value.qid] = value
  353. if _enable_events:
  354. value.events_enabled = True
  355. self.app.fire_event('domain-add', vm=value)
  356. return value
  357. def __getitem__(self, key):
  358. if isinstance(key, int):
  359. return self._dict[key]
  360. if isinstance(key, str):
  361. for vm in self:
  362. if vm.name == key:
  363. return vm
  364. raise KeyError(key)
  365. if isinstance(key, qubes.vm.BaseVM):
  366. key = key.uuid
  367. if isinstance(key, uuid.UUID):
  368. for vm in self:
  369. if vm.uuid == key:
  370. return vm
  371. raise KeyError(key)
  372. raise KeyError(key)
  373. def __delitem__(self, key):
  374. vm = self[key]
  375. if not vm.is_halted():
  376. raise qubes.exc.QubesVMNotHaltedError(vm)
  377. self.app.fire_event('domain-pre-delete', pre_event=True, vm=vm)
  378. try:
  379. vm.libvirt_domain.undefine()
  380. except libvirt.libvirtError as e:
  381. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  382. # already undefined
  383. pass
  384. del self._dict[vm.qid]
  385. self.app.fire_event('domain-delete', vm=vm)
  386. def __contains__(self, key):
  387. return any((key == vm or key == vm.qid or key == vm.name)
  388. for vm in self)
  389. def __len__(self):
  390. return len(self._dict)
  391. def get_vms_based_on(self, template):
  392. template = self[template]
  393. return set(vm for vm in self
  394. if hasattr(vm, 'template') and vm.template == template)
  395. def get_vms_connected_to(self, netvm):
  396. new_vms = set([self[netvm]])
  397. dependent_vms = set()
  398. # Dependency resolving only makes sense on NetVM (or derivative)
  399. # if not self[netvm_qid].is_netvm():
  400. # return set([])
  401. while new_vms:
  402. cur_vm = new_vms.pop()
  403. for vm in cur_vm.connected_vms:
  404. if vm in dependent_vms:
  405. continue
  406. dependent_vms.add(vm)
  407. # if vm.is_netvm():
  408. new_vms.add(vm)
  409. return dependent_vms
  410. # XXX with Qubes Admin Api this will probably lead to race condition
  411. # whole process of creating and adding should be synchronised
  412. def get_new_unused_qid(self):
  413. used_ids = set(self.qids())
  414. for i in range(1, qubes.config.max_qid):
  415. if i not in used_ids:
  416. return i
  417. raise LookupError("Cannot find unused qid!")
  418. def get_new_unused_netid(self):
  419. used_ids = set([vm.netid for vm in self]) # if vm.is_netvm()])
  420. for i in range(1, qubes.config.max_netid):
  421. if i not in used_ids:
  422. return i
  423. raise LookupError("Cannot find unused netid!")
  424. def get_new_unused_dispid(self):
  425. for _ in range(int(qubes.config.max_dispid ** 0.5)):
  426. dispid = random.SystemRandom().randrange(qubes.config.max_dispid)
  427. if not any(getattr(vm, 'dispid', None) == dispid for vm in self):
  428. return dispid
  429. raise LookupError((
  430. 'https://xkcd.com/221/',
  431. 'http://dilbert.com/strip/2001-10-25')[random.randint(0, 1)])
  432. def _default_pool(app):
  433. ''' Default storage pool.
  434. 1. If there is one named 'default', use it.
  435. 2. Check if root fs is on LVM thin - use that
  436. 3. Look for file-based pool pointing /var/lib/qubes
  437. 4. Fail
  438. '''
  439. if 'default' in app.pools:
  440. return app.pools['default']
  441. else:
  442. rootfs = os.stat('/')
  443. root_major = (rootfs.st_dev & 0xff00) >> 8
  444. root_minor = rootfs.st_dev & 0xff
  445. for pool in app.pools.values():
  446. if pool.config.get('driver', None) != 'lvm_thin':
  447. continue
  448. thin_pool = pool.config['thin_pool']
  449. thin_volumes = subprocess.check_output(
  450. ['lvs', '--select', 'pool_lv=' + thin_pool,
  451. '-o', 'lv_kernel_major,lv_kernel_minor', '--noheadings'])
  452. thin_volumes = thin_volumes.decode()
  453. if any([str(root_major), str(root_minor)] == thin_vol.split()
  454. for thin_vol in thin_volumes.splitlines()):
  455. return pool
  456. # not a thin volume? look for file pools
  457. for pool in app.pools.values():
  458. if pool.config.get('driver', None) != 'file':
  459. continue
  460. if pool.config['dir_path'] == qubes.config.qubes_base_dir:
  461. return pool
  462. raise AttributeError('Cannot determine default storage pool')
  463. def _setter_pool(app, prop, value):
  464. if isinstance(value, qubes.storage.Pool):
  465. return value
  466. try:
  467. return app.pools[value]
  468. except KeyError:
  469. raise qubes.exc.QubesPropertyValueError(app, prop, value,
  470. 'No such storage pool')
  471. class Qubes(qubes.PropertyHolder):
  472. '''Main Qubes application
  473. :param str store: path to ``qubes.xml``
  474. The store is loaded in stages:
  475. 1. In the first stage there are loaded some basic features from store
  476. (currently labels).
  477. 2. In the second stage stubs for all VMs are loaded. They are filled
  478. with their basic properties, like ``qid`` and ``name``.
  479. 3. In the third stage all global properties are loaded. They often
  480. reference VMs, like default netvm, so they should be filled after
  481. loading VMs.
  482. 4. In the fourth stage all remaining VM properties are loaded. They
  483. also need all VMs loaded, because they represent dependencies
  484. between VMs like aforementioned netvm.
  485. 5. In the fifth stage there are some fixups to ensure sane system
  486. operation.
  487. This class emits following events:
  488. .. event:: domain-add (subject, event, vm)
  489. When domain is added.
  490. :param subject: Event emitter
  491. :param event: Event name (``'domain-add'``)
  492. :param vm: Domain object
  493. .. event:: domain-pre-delete (subject, event, vm)
  494. When domain is deleted. VM still has reference to ``app`` object,
  495. and is contained within VMCollection. You may prevent removal by
  496. raising an exception.
  497. :param subject: Event emitter
  498. :param event: Event name (``'domain-pre-delete'``)
  499. :param vm: Domain object
  500. .. event:: domain-delete (subject, event, vm)
  501. When domain is deleted. VM still has reference to ``app`` object,
  502. but is not contained within VMCollection.
  503. :param subject: Event emitter
  504. :param event: Event name (``'domain-delete'``)
  505. :param vm: Domain object
  506. Methods and attributes:
  507. '''
  508. default_netvm = qubes.VMProperty('default_netvm', load_stage=3,
  509. default=None, allow_none=True,
  510. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  511. that AppVMs are not connected to the Internet.''')
  512. default_fw_netvm = qubes.VMProperty('default_fw_netvm', load_stage=3,
  513. default=None, allow_none=True,
  514. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  515. that ProxyVMs (including FirewallVM) are not connected to the
  516. Internet.''')
  517. default_template = qubes.VMProperty('default_template', load_stage=3,
  518. vmclass=qubes.vm.templatevm.TemplateVM,
  519. doc='Default template for new AppVMs')
  520. updatevm = qubes.VMProperty('updatevm', load_stage=3,
  521. allow_none=True,
  522. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  523. TemplateVMs''')
  524. clockvm = qubes.VMProperty('clockvm', load_stage=3,
  525. default=None, allow_none=True,
  526. doc='Which VM to use as NTP proxy for updating AdminVM')
  527. default_kernel = qubes.property('default_kernel', load_stage=3,
  528. doc='Which kernel to use when not overriden in VM')
  529. default_dispvm = qubes.VMProperty('default_dispvm', load_stage=3,
  530. doc='Default DispVM base for service calls')
  531. default_pool = qubes.property('default_pool', load_stage=3,
  532. default=_default_pool,
  533. setter=_setter_pool,
  534. doc='Default storage pool')
  535. default_pool_private = qubes.property('default_pool_private', load_stage=3,
  536. default=lambda app: app.default_pool,
  537. setter=_setter_pool,
  538. doc='Default storage pool for private volumes')
  539. default_pool_root = qubes.property('default_pool_root', load_stage=3,
  540. default=lambda app: app.default_pool,
  541. setter=_setter_pool,
  542. doc='Default storage pool for root volumes')
  543. default_pool_volatile = qubes.property('default_pool_volatile',
  544. load_stage=3,
  545. default=lambda app: app.default_pool,
  546. setter=_setter_pool,
  547. doc='Default storage pool for volatile volumes')
  548. default_pool_kernel = qubes.property('default_pool_kernel', load_stage=3,
  549. default=lambda app: app.default_pool,
  550. setter=_setter_pool,
  551. doc='Default storage pool for kernel volumes')
  552. stats_interval = qubes.property('stats_interval',
  553. default=3,
  554. type=int,
  555. doc='Interval in seconds for VM stats reporting (memory, CPU usage)')
  556. # TODO #1637 #892
  557. check_updates_vm = qubes.property('check_updates_vm',
  558. type=bool, setter=qubes.property.bool,
  559. default=True,
  560. doc='check for updates inside qubes')
  561. def __init__(self, store=None, load=True, offline_mode=None, lock=False,
  562. **kwargs):
  563. #: logger instance for logging global messages
  564. self.log = logging.getLogger('app')
  565. self.log.debug('init() -> %#x', id(self))
  566. self.log.debug('stack:')
  567. for frame in traceback.extract_stack():
  568. self.log.debug('%s', frame)
  569. self._extensions = qubes.ext.get_extensions()
  570. #: collection of all VMs managed by this Qubes instance
  571. self.domains = VMCollection(self)
  572. #: collection of all available labels for VMs
  573. self.labels = {}
  574. #: collection of all pools
  575. self.pools = {}
  576. #: Connection to VMM
  577. self.vmm = VMMConnection(offline_mode=offline_mode)
  578. #: Information about host system
  579. self.host = QubesHost(self)
  580. if store is not None:
  581. self._store = store
  582. else:
  583. self._store = os.environ.get('QUBES_XML_PATH',
  584. os.path.join(
  585. qubes.config.qubes_base_dir,
  586. qubes.config.system_path['qubes_store_filename']))
  587. super(Qubes, self).__init__(xml=None, **kwargs)
  588. self.__load_timestamp = None
  589. self.__locked_fh = None
  590. self._domain_event_callback_id = None
  591. #: jinja2 environment for libvirt XML templates
  592. self.env = jinja2.Environment(
  593. loader=jinja2.FileSystemLoader([
  594. '/etc/qubes/templates',
  595. '/usr/share/qubes/templates',
  596. ]),
  597. undefined=jinja2.StrictUndefined)
  598. if load:
  599. self.load(lock=lock)
  600. self.events_enabled = True
  601. @property
  602. def store(self):
  603. return self._store
  604. def load(self, lock=False):
  605. '''Open qubes.xml
  606. :throws EnvironmentError: failure on parsing store
  607. :throws xml.parsers.expat.ExpatError: failure on parsing store
  608. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  609. '''
  610. fh = self._acquire_lock()
  611. self.xml = lxml.etree.parse(fh)
  612. # stage 1: load labels and pools
  613. for node in self.xml.xpath('./labels/label'):
  614. label = qubes.Label.fromxml(node)
  615. self.labels[label.index] = label
  616. for node in self.xml.xpath('./pools/pool'):
  617. name = node.get('name')
  618. assert name, "Pool name '%s' is invalid " % name
  619. try:
  620. self.pools[name] = self._get_pool(**node.attrib)
  621. except qubes.exc.QubesException as e:
  622. self.log.error(str(e))
  623. # stage 2: load VMs
  624. for node in self.xml.xpath('./domains/domain'):
  625. # pylint: disable=no-member
  626. cls = self.get_vm_class(node.get('class'))
  627. vm = cls(self, node)
  628. vm.load_properties(load_stage=2)
  629. vm.init_log()
  630. self.domains.add(vm, _enable_events=False)
  631. if 0 not in self.domains:
  632. self.domains.add(
  633. qubes.vm.adminvm.AdminVM(self, None, qid=0, name='dom0'),
  634. _enable_events=False)
  635. # stage 3: load global properties
  636. self.load_properties(load_stage=3)
  637. # stage 4: fill all remaining VM properties
  638. for vm in self.domains:
  639. vm.load_properties(load_stage=4)
  640. vm.load_extras()
  641. # stage 5: misc fixups
  642. self.property_require('default_fw_netvm', allow_none=True)
  643. self.property_require('default_netvm', allow_none=True)
  644. self.property_require('default_template')
  645. self.property_require('clockvm', allow_none=True)
  646. self.property_require('updatevm', allow_none=True)
  647. for vm in self.domains:
  648. vm.events_enabled = True
  649. vm.fire_event('domain-load')
  650. # get a file timestamp (before closing it - still holding the lock!),
  651. # to detect whether anyone else have modified it in the meantime
  652. self.__load_timestamp = os.path.getmtime(self._store)
  653. if not lock:
  654. self._release_lock()
  655. def __xml__(self):
  656. element = lxml.etree.Element('qubes')
  657. element.append(self.xml_labels())
  658. pools_xml = lxml.etree.Element('pools')
  659. for pool in self.pools.values():
  660. xml = pool.__xml__()
  661. if xml is not None:
  662. pools_xml.append(xml)
  663. element.append(pools_xml)
  664. element.append(self.xml_properties())
  665. domains = lxml.etree.Element('domains')
  666. for vm in self.domains:
  667. domains.append(vm.__xml__())
  668. element.append(domains)
  669. return element
  670. def save(self, lock=True):
  671. '''Save all data to qubes.xml
  672. There are several problems with saving :file:`qubes.xml` which must be
  673. mitigated:
  674. - Running out of disk space. No space left should not result in empty
  675. file. This is done by writing to temporary file and then renaming.
  676. - Attempts to write two or more files concurrently. This is done by
  677. sophisticated locking.
  678. :param bool lock: keep file locked after saving
  679. :throws EnvironmentError: failure on saving
  680. '''
  681. if not self.__locked_fh:
  682. self._acquire_lock(for_save=True)
  683. fh_new = tempfile.NamedTemporaryFile(
  684. prefix=self._store, delete=False)
  685. lxml.etree.ElementTree(self.__xml__()).write(
  686. fh_new, encoding='utf-8', pretty_print=True)
  687. fh_new.flush()
  688. try:
  689. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  690. os.chmod(fh_new.name, 0o660)
  691. except KeyError: # group 'qubes' not found
  692. # don't change mode if no 'qubes' group in the system
  693. pass
  694. os.rename(fh_new.name, self._store)
  695. # update stored mtime, in case of multiple save() calls without
  696. # loading qubes.xml again
  697. self.__load_timestamp = os.path.getmtime(self._store)
  698. # this releases lock for all other processes,
  699. # but they should instantly block on the new descriptor
  700. self.__locked_fh.close()
  701. self.__locked_fh = fh_new
  702. if not lock:
  703. self._release_lock()
  704. def close(self):
  705. '''Deconstruct the object and break circular references
  706. After calling this the object is unusable, not even for saving.'''
  707. self.log.debug('close() <- %#x', id(self))
  708. for frame in traceback.extract_stack():
  709. self.log.debug('%s', frame)
  710. super().close()
  711. if self._domain_event_callback_id is not None:
  712. self.vmm.libvirt_conn.domainEventDeregisterAny(
  713. self._domain_event_callback_id)
  714. self._domain_event_callback_id = None
  715. # Only our Lord, The God Almighty, knows what references
  716. # are kept in extensions.
  717. del self._extensions
  718. for vm in self.domains:
  719. vm.close()
  720. self.domains.close()
  721. del self.domains
  722. self.vmm.close()
  723. del self.vmm
  724. del self.host
  725. if self.__locked_fh:
  726. self._release_lock()
  727. def _acquire_lock(self, for_save=False):
  728. assert self.__locked_fh is None, 'double lock'
  729. while True:
  730. try:
  731. fd = os.open(self._store,
  732. os.O_RDWR | (os.O_CREAT * int(for_save)))
  733. except OSError as e:
  734. if not for_save and e.errno == errno.ENOENT:
  735. raise qubes.exc.QubesException(
  736. 'Qubes XML store {!r} is missing; '
  737. 'use qubes-create tool'.format(self._store))
  738. raise
  739. # While we were waiting for lock, someone could have unlink()ed
  740. # (or rename()d) our file out of the filesystem. We have to
  741. # ensure we got lock on something linked to filesystem.
  742. # If not, try again.
  743. if os.fstat(fd) != os.stat(self._store):
  744. os.close(fd)
  745. continue
  746. if self.__load_timestamp and \
  747. os.path.getmtime(self._store) != self.__load_timestamp:
  748. os.close(fd)
  749. raise qubes.exc.QubesException(
  750. 'Someone else modified qubes.xml in the meantime')
  751. break
  752. if os.name == 'posix':
  753. fcntl.lockf(fd, fcntl.LOCK_EX)
  754. elif os.name == 'nt':
  755. # pylint: disable=protected-access
  756. overlapped = pywintypes.OVERLAPPED()
  757. win32file.LockFileEx(
  758. win32file._get_osfhandle(fd),
  759. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  760. self.__locked_fh = os.fdopen(fd, 'r+b')
  761. return self.__locked_fh
  762. def _release_lock(self):
  763. assert self.__locked_fh is not None, 'double release'
  764. # intentionally do not call explicit unlock to not unlock the file
  765. # before all buffers are flushed
  766. self.__locked_fh.close()
  767. self.__locked_fh = None
  768. def load_initial_values(self):
  769. self.labels = {
  770. 1: qubes.Label(1, '0xcc0000', 'red'),
  771. 2: qubes.Label(2, '0xf57900', 'orange'),
  772. 3: qubes.Label(3, '0xedd400', 'yellow'),
  773. 4: qubes.Label(4, '0x73d216', 'green'),
  774. 5: qubes.Label(5, '0x555753', 'gray'),
  775. 6: qubes.Label(6, '0x3465a4', 'blue'),
  776. 7: qubes.Label(7, '0x75507b', 'purple'),
  777. 8: qubes.Label(8, '0x000000', 'black'),
  778. }
  779. assert max(self.labels.keys()) == qubes.config.max_default_label
  780. # check if the default LVM Thin pool qubes_dom0/pool00 exists
  781. if os.path.exists('/dev/mapper/qubes_dom0-pool00-tpool'):
  782. self.add_pool(volume_group='qubes_dom0', thin_pool='pool00',
  783. name='lvm', driver='lvm_thin')
  784. # pool based on /var/lib/qubes will be created here:
  785. for name, config in qubes.config.defaults['pool_configs'].items():
  786. self.pools[name] = self._get_pool(**config)
  787. self.default_pool_kernel = 'linux-kernel'
  788. self.domains.add(
  789. qubes.vm.adminvm.AdminVM(self, None, label='black'))
  790. @classmethod
  791. def create_empty_store(cls, *args, **kwargs):
  792. self = cls(*args, load=False, **kwargs)
  793. if os.path.exists(self.store):
  794. raise qubes.exc.QubesException(
  795. '{} already exists, aborting'.format(self.store))
  796. self.load_initial_values()
  797. # TODO py3 get lock= as keyword-only arg
  798. self.save(kwargs.get('lock'))
  799. return self
  800. def xml_labels(self):
  801. '''Serialise labels
  802. :rtype: lxml.etree._Element
  803. '''
  804. labels = lxml.etree.Element('labels')
  805. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  806. labels.append(label.__xml__())
  807. return labels
  808. @staticmethod
  809. def get_vm_class(clsname):
  810. '''Find the class for a domain.
  811. Classes are registered as setuptools' entry points in ``qubes.vm``
  812. group. Any package may supply their own classes.
  813. :param str clsname: name of the class
  814. :return type: class
  815. '''
  816. try:
  817. return qubes.utils.get_entry_point_one(
  818. qubes.vm.VM_ENTRY_POINT, clsname)
  819. except KeyError:
  820. raise qubes.exc.QubesException(
  821. 'no such VM class: {!r}'.format(clsname))
  822. # don't catch TypeError
  823. def add_new_vm(self, cls, qid=None, **kwargs):
  824. '''Add new Virtual Machine to collection
  825. '''
  826. if qid is None:
  827. qid = self.domains.get_new_unused_qid()
  828. if isinstance(cls, str):
  829. cls = self.get_vm_class(cls)
  830. # handle default template; specifically allow template=None (do not
  831. # override it with default template)
  832. if 'template' not in kwargs and hasattr(cls, 'template'):
  833. kwargs['template'] = self.default_template
  834. elif 'template' in kwargs and isinstance(kwargs['template'], str):
  835. kwargs['template'] = self.domains[kwargs['template']]
  836. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  837. def get_label(self, label):
  838. '''Get label as identified by index or name
  839. :throws KeyError: when label is not found
  840. '''
  841. # first search for index, verbatim
  842. try:
  843. return self.labels[label]
  844. except KeyError:
  845. pass
  846. # then search for name
  847. for i in self.labels.values():
  848. if i.name == label:
  849. return i
  850. # last call, if label is a number represented as str, search in indices
  851. try:
  852. return self.labels[int(label)]
  853. except (KeyError, ValueError):
  854. pass
  855. raise KeyError(label)
  856. def add_pool(self, name, **kwargs):
  857. """ Add a storage pool to config."""
  858. if name in self.pools.keys():
  859. raise qubes.exc.QubesException('pool named %s already exists \n' %
  860. name)
  861. kwargs['name'] = name
  862. pool = self._get_pool(**kwargs)
  863. pool.setup()
  864. self.pools[name] = pool
  865. return pool
  866. def remove_pool(self, name):
  867. """ Remove a storage pool from config file. """
  868. try:
  869. pool = self.pools[name]
  870. del self.pools[name]
  871. pool.destroy()
  872. except KeyError:
  873. return
  874. def get_pool(self, pool):
  875. ''' Returns a :py:class:`qubes.storage.Pool` instance '''
  876. if isinstance(pool, qubes.storage.Pool):
  877. return pool
  878. try:
  879. return self.pools[pool]
  880. except KeyError:
  881. raise qubes.exc.QubesException('Unknown storage pool ' + pool)
  882. @staticmethod
  883. def _get_pool(**kwargs):
  884. try:
  885. name = kwargs['name']
  886. assert name, 'Name needs to be an non empty string'
  887. except KeyError:
  888. raise qubes.exc.QubesException('No pool name for pool')
  889. try:
  890. driver = kwargs['driver']
  891. except KeyError:
  892. raise qubes.exc.QubesException('No driver specified for pool ' +
  893. name)
  894. try:
  895. klass = qubes.utils.get_entry_point_one(
  896. qubes.storage.STORAGE_ENTRY_POINT, driver)
  897. del kwargs['driver']
  898. return klass(**kwargs)
  899. except KeyError:
  900. raise qubes.exc.QubesException('No driver %s for pool %s' %
  901. (driver, name))
  902. def register_event_handlers(self):
  903. '''Register libvirt event handlers, which will translate libvirt
  904. events into qubes.events. This function should be called only in
  905. 'qubesd' process and only when mainloop has been already set.
  906. '''
  907. self._domain_event_callback_id = (
  908. self.vmm.libvirt_conn.domainEventRegisterAny(
  909. None, # any domain
  910. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  911. self._domain_event_callback,
  912. None))
  913. def _domain_event_callback(self, _conn, domain, event, _detail, _opaque):
  914. '''Generic libvirt event handler (virConnectDomainEventCallback),
  915. translate libvirt event into qubes.events.
  916. '''
  917. if not self.events_enabled:
  918. return
  919. try:
  920. vm = self.domains[domain.name()]
  921. except KeyError:
  922. # ignore events for unknown domains
  923. return
  924. if event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  925. vm.fire_event('domain-shutdown')
  926. @qubes.events.handler('domain-pre-delete')
  927. def on_domain_pre_deleted(self, event, vm):
  928. # pylint: disable=unused-argument
  929. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  930. appvms = self.domains.get_vms_based_on(vm)
  931. if appvms:
  932. raise qubes.exc.QubesException(
  933. 'Cannot remove template that has dependent AppVMs. '
  934. 'Affected are: {}'.format(', '.join(
  935. appvm.name for appvm in sorted(appvms))))
  936. @qubes.events.handler('domain-delete')
  937. def on_domain_deleted(self, event, vm):
  938. # pylint: disable=unused-argument
  939. for propname in (
  940. 'default_netvm',
  941. 'default_fw_netvm',
  942. 'clockvm',
  943. 'updatevm',
  944. 'default_template',
  945. ):
  946. try:
  947. if getattr(self, propname) == vm:
  948. delattr(self, propname)
  949. except AttributeError:
  950. pass
  951. @qubes.events.handler('property-pre-set:clockvm')
  952. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  953. # pylint: disable=unused-argument,no-self-use
  954. if newvalue is None:
  955. return
  956. if 'service.clocksync' not in newvalue.features:
  957. newvalue.features['service.clocksync'] = True
  958. @qubes.events.handler('property-set:clockvm')
  959. def on_property_set_clockvm(self, event, name, newvalue, oldvalue=None):
  960. # pylint: disable=unused-argument,no-self-use
  961. if oldvalue and oldvalue.features.get('service.clocksync', False):
  962. del oldvalue.features['service.clocksync']
  963. @qubes.events.handler(
  964. 'property-pre-set:default_netvm',
  965. 'property-pre-set:default_fw_netvm')
  966. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  967. oldvalue=None):
  968. # pylint: disable=unused-argument,invalid-name
  969. if newvalue is not None and oldvalue is not None \
  970. and oldvalue.is_running() and not newvalue.is_running() \
  971. and self.domains.get_vms_connected_to(oldvalue):
  972. raise qubes.exc.QubesVMNotRunningError(newvalue,
  973. 'Cannot change {!r} to domain that '
  974. 'is not running ({!r}).'.format(name, newvalue.name))
  975. @qubes.events.handler('property-set:default_fw_netvm')
  976. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  977. oldvalue=None):
  978. # pylint: disable=unused-argument,invalid-name
  979. for vm in self.domains:
  980. if not vm.provides_network and vm.property_is_default('netvm'):
  981. # fire property-del:netvm as it is responsible for resetting
  982. # netvm to it's default value
  983. vm.fire_event('property-del:netvm',
  984. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  985. @qubes.events.handler('property-set:default_netvm')
  986. def on_property_set_default_netvm(self, event, name, newvalue,
  987. oldvalue=None):
  988. # pylint: disable=unused-argument
  989. for vm in self.domains:
  990. if hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  991. # fire property-del:netvm as it is responsible for resetting
  992. # netvm to it's default value
  993. vm.fire_event('property-del:netvm',
  994. name='netvm', oldvalue=oldvalue)