app.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  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. elif event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED:
  989. try:
  990. vm.fire_event('domain-paused')
  991. except Exception: # pylint: disable=broad-except
  992. self.log.exception(
  993. 'Uncaught exception from domain-paused handler '
  994. 'for domain %s', vm.name)
  995. elif event == libvirt.VIR_DOMAIN_EVENT_RESUMED:
  996. try:
  997. vm.fire_event('domain-unpaused')
  998. except Exception: # pylint: disable=broad-except
  999. self.log.exception(
  1000. 'Uncaught exception from domain-unpaused handler '
  1001. 'for domain %s', vm.name)
  1002. @qubes.events.handler('domain-pre-delete')
  1003. def on_domain_pre_deleted(self, event, vm):
  1004. # pylint: disable=unused-argument
  1005. for obj in itertools.chain(self.domains, (self,)):
  1006. for prop in obj.property_list():
  1007. try:
  1008. if isinstance(prop, qubes.vm.VMProperty) and \
  1009. getattr(obj, prop.__name__) == vm:
  1010. self.log.error(
  1011. 'Cannot remove %s, used by %s.%s',
  1012. vm, obj, prop.__name__)
  1013. raise qubes.exc.QubesVMInUseError(vm,
  1014. 'Domain is in use: {!r}; details in system log'
  1015. .format(vm.name))
  1016. except AttributeError:
  1017. pass
  1018. @qubes.events.handler('domain-delete')
  1019. def on_domain_deleted(self, event, vm):
  1020. # pylint: disable=unused-argument
  1021. for propname in (
  1022. 'default_netvm',
  1023. 'default_fw_netvm',
  1024. 'clockvm',
  1025. 'updatevm',
  1026. 'default_template',
  1027. ):
  1028. try:
  1029. if getattr(self, propname) == vm:
  1030. delattr(self, propname)
  1031. except AttributeError:
  1032. pass
  1033. @qubes.events.handler('property-pre-set:clockvm')
  1034. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1035. # pylint: disable=unused-argument,no-self-use
  1036. if newvalue is None:
  1037. return
  1038. if 'service.clocksync' not in newvalue.features:
  1039. newvalue.features['service.clocksync'] = True
  1040. @qubes.events.handler('property-set:clockvm')
  1041. def on_property_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1042. # pylint: disable=unused-argument,no-self-use
  1043. if oldvalue and oldvalue.features.get('service.clocksync', False):
  1044. del oldvalue.features['service.clocksync']
  1045. @qubes.events.handler('property-pre-set:default_netvm')
  1046. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1047. oldvalue=None):
  1048. # pylint: disable=unused-argument,invalid-name
  1049. if newvalue is not None and oldvalue is not None \
  1050. and oldvalue.is_running() and not newvalue.is_running() \
  1051. and self.domains.get_vms_connected_to(oldvalue):
  1052. raise qubes.exc.QubesVMNotRunningError(newvalue,
  1053. 'Cannot change {!r} to domain that '
  1054. 'is not running ({!r}).'.format(name, newvalue.name))
  1055. @qubes.events.handler('property-set:default_fw_netvm')
  1056. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1057. oldvalue=None):
  1058. # pylint: disable=unused-argument,invalid-name
  1059. for vm in self.domains:
  1060. if hasattr(vm, 'provides_network') and vm.provides_network and \
  1061. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1062. # fire property-del:netvm as it is responsible for resetting
  1063. # netvm to it's default value
  1064. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1065. name='netvm', oldvalue=oldvalue)
  1066. vm.fire_event('property-del:netvm',
  1067. name='netvm', oldvalue=oldvalue)
  1068. @qubes.events.handler('property-set:default_netvm')
  1069. def on_property_set_default_netvm(self, event, name, newvalue,
  1070. oldvalue=None):
  1071. # pylint: disable=unused-argument
  1072. for vm in self.domains:
  1073. if hasattr(vm, 'provides_network') and not vm.provides_network and \
  1074. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1075. # fire property-del:netvm as it is responsible for resetting
  1076. # netvm to it's default value
  1077. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1078. name='netvm', oldvalue=oldvalue)
  1079. vm.fire_event('property-del:netvm',
  1080. name='netvm', oldvalue=oldvalue)