app.py 44 KB

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