app.py 32 KB

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