app.py 35 KB

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