app.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  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 logging
  27. import os
  28. import random
  29. import subprocess
  30. import sys
  31. import tempfile
  32. import time
  33. import traceback
  34. import uuid
  35. import itertools
  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. # 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 == vm or key == vm.qid or key == 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. # pylint: disable=too-few-public-methods
  429. class RootThinPool:
  430. '''The thin pool containing the rootfs device'''
  431. _inited = False
  432. _volume_group = None
  433. _thin_pool = None
  434. @classmethod
  435. def _init(cls):
  436. '''Find out the thin pool containing the root device'''
  437. if not cls._inited:
  438. cls._inited = True
  439. try:
  440. rootfs = os.stat('/')
  441. root_major = (rootfs.st_dev & 0xff00) >> 8
  442. root_minor = rootfs.st_dev & 0xff
  443. root_table = subprocess.check_output(["dmsetup",
  444. "-j", str(root_major), "-m", str(root_minor),
  445. "table"])
  446. _start, _sectors, target_type, target_args = \
  447. root_table.decode().split(" ", 3)
  448. if target_type == "thin":
  449. thin_pool_devnum, _thin_pool_id = target_args.split(" ")
  450. with open("/sys/dev/block/{}/dm/name"
  451. .format(thin_pool_devnum), "r") as thin_pool_tpool_f:
  452. thin_pool_tpool = thin_pool_tpool_f.read().rstrip('\n')
  453. if thin_pool_tpool.endswith("-tpool"):
  454. volume_group, thin_pool, _tpool = \
  455. thin_pool_tpool.rsplit("-", 2)
  456. cls._volume_group = volume_group
  457. cls._thin_pool = thin_pool
  458. except: # pylint: disable=bare-except
  459. pass
  460. @classmethod
  461. def volume_group(cls):
  462. '''Volume group of the thin pool containing the rootfs device'''
  463. cls._init()
  464. return cls._volume_group
  465. @classmethod
  466. def thin_pool(cls):
  467. '''Thin pool name containing the rootfs device'''
  468. cls._init()
  469. return cls._thin_pool
  470. def _default_pool(app):
  471. ''' Default storage pool.
  472. 1. If there is one named 'default', use it.
  473. 2. Check if root fs is on LVM thin - use that
  474. 3. Look for file-based pool pointing /var/lib/qubes
  475. 4. Fail
  476. '''
  477. if 'default' in app.pools:
  478. return app.pools['default']
  479. else:
  480. if 'DEFAULT_LVM_POOL' in os.environ:
  481. thin_pool = os.environ['DEFAULT_LVM_POOL']
  482. for pool in app.pools.values():
  483. if pool.config.get('driver', None) != 'lvm_thin':
  484. continue
  485. if pool.config['thin_pool'] == thin_pool:
  486. return pool
  487. # no DEFAULT_LVM_POOL, or pool not defined
  488. root_volume_group = RootThinPool.volume_group()
  489. root_thin_pool = RootThinPool.thin_pool()
  490. if root_thin_pool:
  491. for pool in app.pools.values():
  492. if pool.config.get('driver', None) != 'lvm_thin':
  493. continue
  494. if (pool.config['volume_group'] == root_volume_group and
  495. pool.config['thin_pool'] == root_thin_pool):
  496. return pool
  497. # not a thin volume? look for file pools
  498. for pool in app.pools.values():
  499. if pool.config.get('driver', None) != 'file':
  500. continue
  501. if pool.config['dir_path'] == qubes.config.qubes_base_dir:
  502. return pool
  503. raise AttributeError('Cannot determine default storage pool')
  504. def _setter_pool(app, prop, value):
  505. if isinstance(value, qubes.storage.Pool):
  506. return value
  507. try:
  508. return app.pools[value]
  509. except KeyError:
  510. raise qubes.exc.QubesPropertyValueError(app, prop, value,
  511. 'No such storage pool')
  512. def _setter_default_netvm(app, prop, value):
  513. # skip netvm loop check while loading qubes.xml, to avoid tricky loading
  514. # order
  515. if not app.events_enabled:
  516. return value
  517. if value is None:
  518. return value
  519. # forbid setting to a value that would result in netvm loop
  520. for vm in app.domains:
  521. if not hasattr(vm, 'netvm'):
  522. continue
  523. if not vm.property_is_default('netvm'):
  524. continue
  525. if value == vm \
  526. or value in app.domains.get_vms_connected_to(vm):
  527. raise qubes.exc.QubesPropertyValueError(app, prop, value,
  528. 'Network loop on \'{!s}\''.format(vm))
  529. return value
  530. class Qubes(qubes.PropertyHolder):
  531. '''Main Qubes application
  532. :param str store: path to ``qubes.xml``
  533. The store is loaded in stages:
  534. 1. In the first stage there are loaded some basic features from store
  535. (currently labels).
  536. 2. In the second stage stubs for all VMs are loaded. They are filled
  537. with their basic properties, like ``qid`` and ``name``.
  538. 3. In the third stage all global properties are loaded. They often
  539. reference VMs, like default netvm, so they should be filled after
  540. loading VMs.
  541. 4. In the fourth stage all remaining VM properties are loaded. They
  542. also need all VMs loaded, because they represent dependencies
  543. between VMs like aforementioned netvm.
  544. 5. In the fifth stage there are some fixups to ensure sane system
  545. operation.
  546. This class emits following events:
  547. .. event:: domain-add (subject, event, vm)
  548. When domain is added.
  549. :param subject: Event emitter
  550. :param event: Event name (``'domain-add'``)
  551. :param vm: Domain object
  552. .. event:: domain-pre-delete (subject, event, vm)
  553. When domain is deleted. VM still has reference to ``app`` object,
  554. and is contained within VMCollection. You may prevent removal by
  555. raising an exception.
  556. :param subject: Event emitter
  557. :param event: Event name (``'domain-pre-delete'``)
  558. :param vm: Domain object
  559. .. event:: domain-delete (subject, event, vm)
  560. When domain is deleted. VM still has reference to ``app`` object,
  561. but is not contained within VMCollection.
  562. :param subject: Event emitter
  563. :param event: Event name (``'domain-delete'``)
  564. :param vm: Domain object
  565. Methods and attributes:
  566. '''
  567. default_netvm = qubes.VMProperty('default_netvm', load_stage=3,
  568. default=None, allow_none=True,
  569. setter=_setter_default_netvm,
  570. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  571. that AppVMs are not connected to the Internet.''')
  572. default_template = qubes.VMProperty('default_template', load_stage=3,
  573. vmclass=qubes.vm.templatevm.TemplateVM,
  574. doc='Default template for new AppVMs')
  575. updatevm = qubes.VMProperty('updatevm', load_stage=3,
  576. allow_none=True,
  577. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  578. TemplateVMs''')
  579. clockvm = qubes.VMProperty('clockvm', load_stage=3,
  580. default=None, allow_none=True,
  581. doc='Which VM to use as NTP proxy for updating AdminVM')
  582. default_kernel = qubes.property('default_kernel', load_stage=3,
  583. doc='Which kernel to use when not overriden in VM')
  584. default_dispvm = qubes.VMProperty('default_dispvm', load_stage=3,
  585. doc='Default DispVM base for service calls', allow_none=True)
  586. default_pool = qubes.property('default_pool', load_stage=3,
  587. default=_default_pool,
  588. setter=_setter_pool,
  589. doc='Default storage pool')
  590. default_pool_private = qubes.property('default_pool_private', load_stage=3,
  591. default=lambda app: app.default_pool,
  592. setter=_setter_pool,
  593. doc='Default storage pool for private volumes')
  594. default_pool_root = qubes.property('default_pool_root', load_stage=3,
  595. default=lambda app: app.default_pool,
  596. setter=_setter_pool,
  597. doc='Default storage pool for root volumes')
  598. default_pool_volatile = qubes.property('default_pool_volatile',
  599. load_stage=3,
  600. default=lambda app: app.default_pool,
  601. setter=_setter_pool,
  602. doc='Default storage pool for volatile volumes')
  603. default_pool_kernel = qubes.property('default_pool_kernel', load_stage=3,
  604. default=lambda app: app.default_pool,
  605. setter=_setter_pool,
  606. doc='Default storage pool for kernel volumes')
  607. stats_interval = qubes.property('stats_interval',
  608. default=3,
  609. type=int,
  610. doc='Interval in seconds for VM stats reporting (memory, CPU usage)')
  611. # TODO #1637 #892
  612. check_updates_vm = qubes.property('check_updates_vm',
  613. type=bool, setter=qubes.property.bool,
  614. default=True,
  615. doc='check for updates inside qubes')
  616. def __init__(self, store=None, load=True, offline_mode=None, lock=False,
  617. **kwargs):
  618. #: logger instance for logging global messages
  619. self.log = logging.getLogger('app')
  620. self.log.debug('init() -> %#x', id(self))
  621. self.log.debug('stack:')
  622. for frame in traceback.extract_stack():
  623. self.log.debug('%s', frame)
  624. self._extensions = qubes.ext.get_extensions()
  625. #: collection of all VMs managed by this Qubes instance
  626. self.domains = VMCollection(self)
  627. #: collection of all available labels for VMs
  628. self.labels = {}
  629. #: collection of all pools
  630. self.pools = {}
  631. #: Connection to VMM
  632. self.vmm = VMMConnection(offline_mode=offline_mode)
  633. #: Information about host system
  634. self.host = QubesHost(self)
  635. if store is not None:
  636. self._store = store
  637. else:
  638. self._store = os.environ.get('QUBES_XML_PATH',
  639. os.path.join(
  640. qubes.config.qubes_base_dir,
  641. qubes.config.system_path['qubes_store_filename']))
  642. super(Qubes, self).__init__(xml=None, **kwargs)
  643. self.__load_timestamp = None
  644. self.__locked_fh = None
  645. self._domain_event_callback_id = None
  646. #: jinja2 environment for libvirt XML templates
  647. self.env = jinja2.Environment(
  648. loader=jinja2.FileSystemLoader([
  649. '/etc/qubes/templates',
  650. '/usr/share/qubes/templates',
  651. ]),
  652. undefined=jinja2.StrictUndefined)
  653. if load:
  654. self.load(lock=lock)
  655. self.events_enabled = True
  656. @property
  657. def store(self):
  658. return self._store
  659. def _migrate_global_properties(self):
  660. '''Migrate renamed/dropped properties'''
  661. if self.xml is None:
  662. return
  663. # drop default_fw_netvm
  664. node_default_fw_netvm = self.xml.find(
  665. './properties/property[@name=\'default_fw_netvm\']')
  666. if node_default_fw_netvm is not None:
  667. node_default_netvm = self.xml.find(
  668. './properties/property[@name=\'default_netvm\']')
  669. try:
  670. default_fw_netvm = self.domains[node_default_fw_netvm.text]
  671. if node_default_netvm is None:
  672. default_netvm = None
  673. else:
  674. default_netvm = self.domains[node_default_netvm.text]
  675. if default_netvm != default_fw_netvm:
  676. for vm in self.domains:
  677. if not hasattr(vm, 'netvm'):
  678. continue
  679. if not getattr(vm, 'provides_network', False):
  680. continue
  681. node_netvm = vm.xml.find(
  682. './properties/property[@name=\'netvm\']')
  683. if node_netvm is not None:
  684. # non-default netvm
  685. continue
  686. # this will unfortunately break "being default"
  687. # property state, but the alternative (changing
  688. # value behind user's back) is worse
  689. properties = vm.xml.find('./properties')
  690. element = lxml.etree.Element('property',
  691. name='netvm')
  692. element.text = default_fw_netvm.name
  693. # manipulate xml directly, before loading netvm
  694. # property, to avoid hitting netvm loop detection
  695. properties.append(element)
  696. except KeyError:
  697. # if default_fw_netvm was set to invalid value, simply
  698. # drop it
  699. pass
  700. node_default_fw_netvm.getparent().remove(node_default_fw_netvm)
  701. def load(self, lock=False):
  702. '''Open qubes.xml
  703. :throws EnvironmentError: failure on parsing store
  704. :throws xml.parsers.expat.ExpatError: failure on parsing store
  705. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  706. '''
  707. fh = self._acquire_lock()
  708. self.xml = lxml.etree.parse(fh)
  709. # stage 1: load labels and pools
  710. for node in self.xml.xpath('./labels/label'):
  711. label = qubes.Label.fromxml(node)
  712. self.labels[label.index] = label
  713. for node in self.xml.xpath('./pools/pool'):
  714. name = node.get('name')
  715. assert name, "Pool name '%s' is invalid " % name
  716. try:
  717. self.pools[name] = self._get_pool(**node.attrib)
  718. except qubes.exc.QubesException as e:
  719. self.log.error(str(e))
  720. # stage 2: load VMs
  721. for node in self.xml.xpath('./domains/domain'):
  722. # pylint: disable=no-member
  723. cls = self.get_vm_class(node.get('class'))
  724. vm = cls(self, node)
  725. vm.load_properties(load_stage=2)
  726. vm.init_log()
  727. self.domains.add(vm, _enable_events=False)
  728. if 0 not in self.domains:
  729. self.domains.add(
  730. qubes.vm.adminvm.AdminVM(self, None),
  731. _enable_events=False)
  732. self._migrate_global_properties()
  733. # stage 3: load global properties
  734. self.load_properties(load_stage=3)
  735. # stage 4: fill all remaining VM properties
  736. for vm in self.domains:
  737. vm.load_properties(load_stage=4)
  738. vm.load_extras()
  739. # stage 5: misc fixups
  740. self.property_require('default_netvm', allow_none=True)
  741. self.property_require('default_template')
  742. self.property_require('clockvm', allow_none=True)
  743. self.property_require('updatevm', allow_none=True)
  744. for vm in self.domains:
  745. vm.events_enabled = True
  746. vm.fire_event('domain-load')
  747. # get a file timestamp (before closing it - still holding the lock!),
  748. # to detect whether anyone else have modified it in the meantime
  749. self.__load_timestamp = os.path.getmtime(self._store)
  750. if not lock:
  751. self._release_lock()
  752. def __xml__(self):
  753. element = lxml.etree.Element('qubes')
  754. element.append(self.xml_labels())
  755. pools_xml = lxml.etree.Element('pools')
  756. for pool in self.pools.values():
  757. xml = pool.__xml__()
  758. if xml is not None:
  759. pools_xml.append(xml)
  760. element.append(pools_xml)
  761. element.append(self.xml_properties())
  762. domains = lxml.etree.Element('domains')
  763. for vm in self.domains:
  764. domains.append(vm.__xml__())
  765. element.append(domains)
  766. return element
  767. def __str__(self):
  768. return type(self).__name__
  769. def save(self, lock=True):
  770. '''Save all data to qubes.xml
  771. There are several problems with saving :file:`qubes.xml` which must be
  772. mitigated:
  773. - Running out of disk space. No space left should not result in empty
  774. file. This is done by writing to temporary file and then renaming.
  775. - Attempts to write two or more files concurrently. This is done by
  776. sophisticated locking.
  777. :param bool lock: keep file locked after saving
  778. :throws EnvironmentError: failure on saving
  779. '''
  780. if not self.__locked_fh:
  781. self._acquire_lock(for_save=True)
  782. fh_new = tempfile.NamedTemporaryFile(
  783. prefix=self._store, delete=False)
  784. lxml.etree.ElementTree(self.__xml__()).write(
  785. fh_new, encoding='utf-8', pretty_print=True)
  786. fh_new.flush()
  787. try:
  788. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  789. os.chmod(fh_new.name, 0o660)
  790. except KeyError: # group 'qubes' not found
  791. # don't change mode if no 'qubes' group in the system
  792. pass
  793. os.rename(fh_new.name, self._store)
  794. # update stored mtime, in case of multiple save() calls without
  795. # loading qubes.xml again
  796. self.__load_timestamp = os.path.getmtime(self._store)
  797. # this releases lock for all other processes,
  798. # but they should instantly block on the new descriptor
  799. self.__locked_fh.close()
  800. self.__locked_fh = fh_new
  801. if not lock:
  802. self._release_lock()
  803. def close(self):
  804. '''Deconstruct the object and break circular references
  805. After calling this the object is unusable, not even for saving.'''
  806. self.log.debug('close() <- %#x', id(self))
  807. for frame in traceback.extract_stack():
  808. self.log.debug('%s', frame)
  809. super().close()
  810. if self._domain_event_callback_id is not None:
  811. self.vmm.libvirt_conn.domainEventDeregisterAny(
  812. self._domain_event_callback_id)
  813. self._domain_event_callback_id = None
  814. # Only our Lord, The God Almighty, knows what references
  815. # are kept in extensions.
  816. del self._extensions
  817. for vm in self.domains:
  818. vm.close()
  819. self.domains.close()
  820. del self.domains
  821. self.vmm.close()
  822. del self.vmm
  823. del self.host
  824. if self.__locked_fh:
  825. self._release_lock()
  826. def _acquire_lock(self, for_save=False):
  827. assert self.__locked_fh is None, 'double lock'
  828. while True:
  829. try:
  830. fd = os.open(self._store,
  831. os.O_RDWR | (os.O_CREAT * int(for_save)))
  832. except OSError as e:
  833. if not for_save and e.errno == errno.ENOENT:
  834. raise qubes.exc.QubesException(
  835. 'Qubes XML store {!r} is missing; '
  836. 'use qubes-create tool'.format(self._store))
  837. raise
  838. # While we were waiting for lock, someone could have unlink()ed
  839. # (or rename()d) our file out of the filesystem. We have to
  840. # ensure we got lock on something linked to filesystem.
  841. # If not, try again.
  842. if os.fstat(fd) != os.stat(self._store):
  843. os.close(fd)
  844. continue
  845. if self.__load_timestamp and \
  846. os.path.getmtime(self._store) != self.__load_timestamp:
  847. os.close(fd)
  848. raise qubes.exc.QubesException(
  849. 'Someone else modified qubes.xml in the meantime')
  850. break
  851. if os.name == 'posix':
  852. fcntl.lockf(fd, fcntl.LOCK_EX)
  853. elif os.name == 'nt':
  854. # pylint: disable=protected-access
  855. overlapped = pywintypes.OVERLAPPED()
  856. win32file.LockFileEx(
  857. win32file._get_osfhandle(fd),
  858. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  859. self.__locked_fh = os.fdopen(fd, 'r+b')
  860. return self.__locked_fh
  861. def _release_lock(self):
  862. assert self.__locked_fh is not None, 'double release'
  863. # intentionally do not call explicit unlock to not unlock the file
  864. # before all buffers are flushed
  865. self.__locked_fh.close()
  866. self.__locked_fh = None
  867. def load_initial_values(self):
  868. self.labels = {
  869. 1: qubes.Label(1, '0xcc0000', 'red'),
  870. 2: qubes.Label(2, '0xf57900', 'orange'),
  871. 3: qubes.Label(3, '0xedd400', 'yellow'),
  872. 4: qubes.Label(4, '0x73d216', 'green'),
  873. 5: qubes.Label(5, '0x555753', 'gray'),
  874. 6: qubes.Label(6, '0x3465a4', 'blue'),
  875. 7: qubes.Label(7, '0x75507b', 'purple'),
  876. 8: qubes.Label(8, '0x000000', 'black'),
  877. }
  878. assert max(self.labels.keys()) == qubes.config.max_default_label
  879. root_volume_group = RootThinPool.volume_group()
  880. root_thin_pool = RootThinPool.thin_pool()
  881. if root_thin_pool:
  882. self.add_pool(
  883. volume_group=root_volume_group, thin_pool=root_thin_pool,
  884. name='lvm', driver='lvm_thin')
  885. # pool based on /var/lib/qubes will be created here:
  886. for name, config in qubes.config.defaults['pool_configs'].items():
  887. self.pools[name] = self._get_pool(**config)
  888. self.default_pool_kernel = 'linux-kernel'
  889. self.domains.add(
  890. qubes.vm.adminvm.AdminVM(self, None, label='black'))
  891. @classmethod
  892. def create_empty_store(cls, *args, **kwargs):
  893. self = cls(*args, load=False, **kwargs)
  894. if os.path.exists(self.store):
  895. raise qubes.exc.QubesException(
  896. '{} already exists, aborting'.format(self.store))
  897. self.load_initial_values()
  898. # TODO py3 get lock= as keyword-only arg
  899. self.save(kwargs.get('lock'))
  900. return self
  901. def xml_labels(self):
  902. '''Serialise labels
  903. :rtype: lxml.etree._Element
  904. '''
  905. labels = lxml.etree.Element('labels')
  906. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  907. labels.append(label.__xml__())
  908. return labels
  909. @staticmethod
  910. def get_vm_class(clsname):
  911. '''Find the class for a domain.
  912. Classes are registered as setuptools' entry points in ``qubes.vm``
  913. group. Any package may supply their own classes.
  914. :param str clsname: name of the class
  915. :return type: class
  916. '''
  917. try:
  918. return qubes.utils.get_entry_point_one(
  919. qubes.vm.VM_ENTRY_POINT, clsname)
  920. except KeyError:
  921. raise qubes.exc.QubesException(
  922. 'no such VM class: {!r}'.format(clsname))
  923. # don't catch TypeError
  924. def add_new_vm(self, cls, qid=None, **kwargs):
  925. '''Add new Virtual Machine to collection
  926. '''
  927. if qid is None:
  928. qid = self.domains.get_new_unused_qid()
  929. if isinstance(cls, str):
  930. cls = self.get_vm_class(cls)
  931. # handle default template; specifically allow template=None (do not
  932. # override it with default template)
  933. if 'template' not in kwargs and hasattr(cls, 'template'):
  934. if cls == self.get_vm_class('DispVM'):
  935. kwargs['template'] = self.default_dispvm
  936. else:
  937. kwargs['template'] = self.default_template
  938. elif 'template' in kwargs and isinstance(kwargs['template'], str):
  939. kwargs['template'] = self.domains[kwargs['template']]
  940. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  941. def get_label(self, label):
  942. '''Get label as identified by index or name
  943. :throws KeyError: when label is not found
  944. '''
  945. # first search for index, verbatim
  946. try:
  947. return self.labels[label]
  948. except KeyError:
  949. pass
  950. # then search for name
  951. for i in self.labels.values():
  952. if i.name == label:
  953. return i
  954. # last call, if label is a number represented as str, search in indices
  955. try:
  956. return self.labels[int(label)]
  957. except (KeyError, ValueError):
  958. pass
  959. raise KeyError(label)
  960. def add_pool(self, name, **kwargs):
  961. """ Add a storage pool to config."""
  962. if name in self.pools.keys():
  963. raise qubes.exc.QubesException('pool named %s already exists \n' %
  964. name)
  965. kwargs['name'] = name
  966. pool = self._get_pool(**kwargs)
  967. pool.setup()
  968. self.pools[name] = pool
  969. return pool
  970. def remove_pool(self, name):
  971. """ Remove a storage pool from config file. """
  972. try:
  973. pool = self.pools[name]
  974. del self.pools[name]
  975. pool.destroy()
  976. except KeyError:
  977. return
  978. def get_pool(self, pool):
  979. ''' Returns a :py:class:`qubes.storage.Pool` instance '''
  980. if isinstance(pool, qubes.storage.Pool):
  981. return pool
  982. try:
  983. return self.pools[pool]
  984. except KeyError:
  985. raise qubes.exc.QubesException('Unknown storage pool ' + pool)
  986. @staticmethod
  987. def _get_pool(**kwargs):
  988. try:
  989. name = kwargs['name']
  990. assert name, 'Name needs to be an non empty string'
  991. except KeyError:
  992. raise qubes.exc.QubesException('No pool name for pool')
  993. try:
  994. driver = kwargs['driver']
  995. except KeyError:
  996. raise qubes.exc.QubesException('No driver specified for pool ' +
  997. name)
  998. try:
  999. klass = qubes.utils.get_entry_point_one(
  1000. qubes.storage.STORAGE_ENTRY_POINT, driver)
  1001. del kwargs['driver']
  1002. return klass(**kwargs)
  1003. except KeyError:
  1004. raise qubes.exc.QubesException('No driver %s for pool %s' %
  1005. (driver, name))
  1006. def register_event_handlers(self):
  1007. '''Register libvirt event handlers, which will translate libvirt
  1008. events into qubes.events. This function should be called only in
  1009. 'qubesd' process and only when mainloop has been already set.
  1010. '''
  1011. self._domain_event_callback_id = (
  1012. self.vmm.libvirt_conn.domainEventRegisterAny(
  1013. None, # any domain
  1014. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  1015. self._domain_event_callback,
  1016. None))
  1017. def _domain_event_callback(self, _conn, domain, event, _detail, _opaque):
  1018. '''Generic libvirt event handler (virConnectDomainEventCallback),
  1019. translate libvirt event into qubes.events.
  1020. '''
  1021. if not self.events_enabled:
  1022. return
  1023. try:
  1024. vm = self.domains[domain.name()]
  1025. except KeyError:
  1026. # ignore events for unknown domains
  1027. return
  1028. if event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  1029. vm.on_libvirt_domain_stopped()
  1030. @qubes.events.handler('domain-pre-delete')
  1031. def on_domain_pre_deleted(self, event, vm):
  1032. # pylint: disable=unused-argument
  1033. for obj in itertools.chain(self.domains, (self,)):
  1034. for prop in obj.property_list():
  1035. try:
  1036. if isinstance(prop, qubes.vm.VMProperty) and \
  1037. getattr(obj, prop.__name__) == vm:
  1038. self.log.error(
  1039. 'Cannot remove %s, used by %s.%s',
  1040. vm, obj, prop.__name__)
  1041. raise qubes.exc.QubesVMInUseError(vm,
  1042. 'Domain is in use: {!r}; details in system log'
  1043. .format(vm.name))
  1044. except AttributeError:
  1045. pass
  1046. @qubes.events.handler('domain-delete')
  1047. def on_domain_deleted(self, event, vm):
  1048. # pylint: disable=unused-argument
  1049. for propname in (
  1050. 'default_netvm',
  1051. 'default_fw_netvm',
  1052. 'clockvm',
  1053. 'updatevm',
  1054. 'default_template',
  1055. ):
  1056. try:
  1057. if getattr(self, propname) == vm:
  1058. delattr(self, propname)
  1059. except AttributeError:
  1060. pass
  1061. @qubes.events.handler('property-pre-set:clockvm')
  1062. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1063. # pylint: disable=unused-argument,no-self-use
  1064. if newvalue is None:
  1065. return
  1066. if 'service.clocksync' not in newvalue.features:
  1067. newvalue.features['service.clocksync'] = True
  1068. @qubes.events.handler('property-set:clockvm')
  1069. def on_property_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1070. # pylint: disable=unused-argument,no-self-use
  1071. if oldvalue and oldvalue.features.get('service.clocksync', False):
  1072. del oldvalue.features['service.clocksync']
  1073. @qubes.events.handler('property-pre-set:default_netvm')
  1074. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1075. oldvalue=None):
  1076. # pylint: disable=unused-argument,invalid-name
  1077. if newvalue is not None and oldvalue is not None \
  1078. and oldvalue.is_running() and not newvalue.is_running() \
  1079. and self.domains.get_vms_connected_to(oldvalue):
  1080. raise qubes.exc.QubesVMNotRunningError(newvalue,
  1081. 'Cannot change {!r} to domain that '
  1082. 'is not running ({!r}).'.format(name, newvalue.name))
  1083. @qubes.events.handler('property-set:default_fw_netvm')
  1084. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1085. oldvalue=None):
  1086. # pylint: disable=unused-argument,invalid-name
  1087. for vm in self.domains:
  1088. if hasattr(vm, 'provides_network') and vm.provides_network and \
  1089. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1090. # fire property-del:netvm as it is responsible for resetting
  1091. # netvm to it's default value
  1092. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1093. name='netvm', oldvalue=oldvalue)
  1094. vm.fire_event('property-del:netvm',
  1095. name='netvm', oldvalue=oldvalue)
  1096. @qubes.events.handler('property-set:default_netvm')
  1097. def on_property_set_default_netvm(self, event, name, newvalue,
  1098. oldvalue=None):
  1099. # pylint: disable=unused-argument
  1100. for vm in self.domains:
  1101. if hasattr(vm, 'provides_network') and not vm.provides_network and \
  1102. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1103. # fire property-del:netvm as it is responsible for resetting
  1104. # netvm to it's default value
  1105. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1106. name='netvm', oldvalue=oldvalue)
  1107. vm.fire_event('property-del:netvm',
  1108. name='netvm', oldvalue=oldvalue)