app.py 36 KB

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