__init__.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2013-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. """ Qubes storage system"""
  23. from __future__ import absolute_import
  24. import inspect
  25. import os
  26. import os.path
  27. import string # pylint: disable=deprecated-module
  28. import time
  29. from datetime import datetime
  30. import asyncio
  31. import lxml.etree
  32. import pkg_resources
  33. import qubes
  34. import qubes.exc
  35. import qubes.utils
  36. STORAGE_ENTRY_POINT = 'qubes.storage'
  37. class StoragePoolException(qubes.exc.QubesException):
  38. ''' A general storage exception '''
  39. pass
  40. class BlockDevice(object):
  41. ''' Represents a storage block device. '''
  42. # pylint: disable=too-few-public-methods
  43. def __init__(self, path, name, script=None, rw=True, domain=None,
  44. devtype='disk'):
  45. assert name, 'Missing device name'
  46. assert path, 'Missing device path'
  47. self.path = path
  48. self.name = name
  49. self.rw = rw
  50. self.script = script
  51. self.domain = domain
  52. self.devtype = devtype
  53. class Volume(object):
  54. ''' Encapsulates all data about a volume for serialization to qubes.xml and
  55. libvirt config.
  56. Keep in mind!
  57. volatile = not snap_on_start and not save_on_stop
  58. snapshot = snap_on_start and not save_on_stop
  59. origin = not snap_on_start and save_on_stop
  60. origin_snapshot = snap_on_start and save_on_stop
  61. '''
  62. devtype = 'disk'
  63. domain = None
  64. path = None
  65. script = None
  66. #: disk space used by this volume, can be smaller than :py:attr:`size`
  67. #: for sparse volumes
  68. usage = 0
  69. def __init__(self, name, pool, vid,
  70. revisions_to_keep=0, rw=False, save_on_stop=False, size=0,
  71. snap_on_start=False, source=None, **kwargs):
  72. ''' Initialize a volume.
  73. :param str name: The name of the volume inside owning domain
  74. :param Pool pool: The pool object
  75. :param str vid: Volume identifier needs to be unique in pool
  76. :param int revisions_to_keep: Amount of revisions to keep around
  77. :param bool rw: If true volume will be mounted read-write
  78. :param bool snap_on_start: Create a snapshot from source on
  79. start, instead of using volume own data
  80. :param bool save_on_stop: Write changes to the volume in
  81. vm.stop(), otherwise - discard
  82. :param Volume source: other volume in same pool to make snapshot
  83. from, required if *snap_on_start*=`True`
  84. :param str/int size: Size of the volume
  85. '''
  86. super(Volume, self).__init__(**kwargs)
  87. assert isinstance(pool, Pool)
  88. assert source is None or (isinstance(source, Volume)
  89. and source.pool == pool)
  90. if snap_on_start and source is None:
  91. msg = "snap_on_start specified on {!r} but no volume source set"
  92. msg = msg.format(name)
  93. raise StoragePoolException(msg)
  94. elif not snap_on_start and source is not None:
  95. msg = "source specified on {!r} but no snap_on_start set"
  96. msg = msg.format(name)
  97. raise StoragePoolException(msg)
  98. #: Name of the volume in a domain it's attached to (like `root` or
  99. #: `private`).
  100. self.name = str(name)
  101. #: :py:class:`Pool` instance owning this volume
  102. self.pool = pool
  103. #: How many revisions of the volume to keep. Each revision is created
  104. # at :py:meth:`stop`, if :py:attr:`save_on_stop` is True
  105. self.revisions_to_keep = int(revisions_to_keep)
  106. #: Should this volume be writable by domain.
  107. self.rw = rw
  108. #: Should volume state be saved or discarded at :py:meth:`stop`
  109. self.save_on_stop = save_on_stop
  110. self._size = int(size)
  111. #: Should the volume state be initialized with a snapshot of
  112. #: same-named volume of domain's template.
  113. self.snap_on_start = snap_on_start
  114. #: source volume for :py:attr:`snap_on_start` volumes
  115. self.source = source
  116. #: Volume unique (inside given pool) identifier
  117. self.vid = vid
  118. def __eq__(self, other):
  119. if isinstance(other, Volume):
  120. return other.pool == self.pool and other.vid == self.vid
  121. return NotImplemented
  122. def __hash__(self):
  123. return hash('%s:%s' % (self.pool, self.vid))
  124. def __neq__(self, other):
  125. return not self.__eq__(other)
  126. def __repr__(self):
  127. return '{!r}'.format(str(self.pool) + ':' + self.vid)
  128. def __str__(self):
  129. return str(self.vid)
  130. def __xml__(self):
  131. config = _sanitize_config(self.config)
  132. return lxml.etree.Element('volume', **config)
  133. def create(self):
  134. ''' Create the given volume on disk.
  135. This method is called only once in the volume lifetime. Before
  136. calling this method, no data on disk should be touched (in
  137. context of this volume).
  138. This can be implemented as a coroutine.
  139. '''
  140. raise self._not_implemented("create")
  141. def remove(self):
  142. ''' Remove volume.
  143. This can be implemented as a coroutine.'''
  144. raise self._not_implemented("remove")
  145. def export(self):
  146. ''' Returns a path to read the volume data from.
  147. Reading from this path when domain owning this volume is
  148. running (i.e. when :py:meth:`is_dirty` is True) should return the
  149. data from before domain startup.
  150. Reading from the path returned by this method should return the
  151. volume data. If extracting volume data require something more
  152. than just reading from file (for example connecting to some other
  153. domain, or decompressing the data), the returned path may be a pipe.
  154. '''
  155. raise self._not_implemented("export")
  156. def import_data(self):
  157. ''' Returns a path to overwrite volume data.
  158. This method is called after volume was already :py:meth:`create`-ed.
  159. Writing to this path should overwrite volume data. If importing
  160. volume data require something more than just writing to a file (
  161. for example connecting to some other domain, or converting data
  162. on the fly), the returned path may be a pipe.
  163. '''
  164. raise self._not_implemented("import")
  165. def import_data_end(self, success):
  166. ''' End the data import operation. This may be used by pool
  167. implementation to commit changes, cleanup temporary files etc.
  168. This method is called regardless the operation was successful or not.
  169. :param success: True if data import was successful, otherwise False
  170. '''
  171. # by default do nothing
  172. pass
  173. def import_volume(self, src_volume):
  174. ''' Imports data from a different volume (possibly in a different
  175. pool.
  176. The volume needs to be create()d first.
  177. This can be implemented as a coroutine. '''
  178. # pylint: disable=unused-argument
  179. raise self._not_implemented("import_volume")
  180. def is_dirty(self):
  181. ''' Return `True` if volume was not properly shutdown and committed.
  182. This include the situation when domain owning the volume is still
  183. running.
  184. '''
  185. raise self._not_implemented("is_dirty")
  186. def is_outdated(self):
  187. ''' Returns `True` if this snapshot of a source volume (for
  188. `snap_on_start`=True) is outdated.
  189. '''
  190. raise self._not_implemented("is_outdated")
  191. def resize(self, size):
  192. ''' Expands volume, throws
  193. :py:class:`qubes.storage.StoragePoolException` if
  194. given size is less than current_size
  195. This can be implemented as a coroutine.
  196. :param int size: new size in bytes
  197. '''
  198. # pylint: disable=unused-argument
  199. raise self._not_implemented("resize")
  200. def revert(self, revision=None):
  201. ''' Revert volume to previous revision
  202. :param revision: revision to revert volume to, see :py:attr:`revisions`
  203. '''
  204. # pylint: disable=unused-argument
  205. raise self._not_implemented("revert")
  206. def start(self):
  207. ''' Do what ever is needed on start.
  208. This include making a snapshot of template's volume if
  209. :py:attr:`snap_on_start` is set.
  210. This can be implemented as a coroutine.'''
  211. raise self._not_implemented("start")
  212. def stop(self):
  213. ''' Do what ever is needed on stop.
  214. This include committing data if :py:attr:`save_on_stop` is set.
  215. This can be implemented as a coroutine.'''
  216. def verify(self):
  217. ''' Verifies the volume.
  218. This can be implemented as a coroutine.'''
  219. raise self._not_implemented("verify")
  220. def block_device(self):
  221. ''' Return :py:class:`BlockDevice` for serialization in
  222. the libvirt XML template as <disk>.
  223. '''
  224. return BlockDevice(self.path, self.name, self.script,
  225. self.rw, self.domain, self.devtype)
  226. @property
  227. def revisions(self):
  228. ''' Returns a dict containing revision identifiers and time of their
  229. creation '''
  230. msg = "{!s} has revisions not implemented".format(self.__class__)
  231. raise NotImplementedError(msg)
  232. @property
  233. def size(self):
  234. ''' Volume size in bytes '''
  235. return self._size
  236. @size.setter
  237. def size(self, size):
  238. # pylint: disable=attribute-defined-outside-init
  239. self._size = int(size)
  240. @property
  241. def config(self):
  242. ''' return config data for serialization to qubes.xml '''
  243. result = {
  244. 'name': self.name,
  245. 'pool': str(self.pool),
  246. 'vid': self.vid,
  247. 'revisions_to_keep': self.revisions_to_keep,
  248. 'rw': self.rw,
  249. 'save_on_stop': self.save_on_stop,
  250. 'snap_on_start': self.snap_on_start,
  251. }
  252. if self.size:
  253. result['size'] = self.size
  254. if self.source:
  255. result['source'] = str(self.source)
  256. return result
  257. def _not_implemented(self, method_name):
  258. ''' Helper for emitting helpful `NotImplementedError` exceptions '''
  259. msg = "Volume {!s} has {!s}() not implemented"
  260. msg = msg.format(str(self.__class__.__name__), method_name)
  261. return NotImplementedError(msg)
  262. class Storage(object):
  263. ''' Class for handling VM virtual disks.
  264. This is base class for all other implementations, mostly with Xen on Linux
  265. in mind.
  266. '''
  267. AVAILABLE_FRONTENDS = set(['xvd' + c for c in string.ascii_lowercase])
  268. def __init__(self, vm):
  269. #: Domain for which we manage storage
  270. self.vm = vm
  271. self.log = self.vm.log
  272. #: Additional drive (currently used only by HVM)
  273. self.drive = None
  274. if hasattr(vm, 'volume_config'):
  275. for name, conf in self.vm.volume_config.items():
  276. self.init_volume(name, conf)
  277. def _update_volume_config_source(self, name, volume_config):
  278. '''Retrieve 'source' volume from VM's template'''
  279. template = getattr(self.vm, 'template', None)
  280. # recursively lookup source volume - templates may be
  281. # chained (TemplateVM -> AppVM -> DispVM, where the
  282. # actual source should be used from TemplateVM)
  283. while template:
  284. source = template.volumes[name]
  285. volume_config['source'] = source
  286. volume_config['pool'] = source.pool
  287. volume_config['size'] = source.size
  288. if source.source is not None:
  289. template = getattr(template, 'template', None)
  290. else:
  291. break
  292. def init_volume(self, name, volume_config):
  293. ''' Initialize Volume instance attached to this domain '''
  294. if 'name' not in volume_config:
  295. volume_config['name'] = name
  296. if 'source' in volume_config:
  297. # we have no control over VM load order,
  298. # so initialize storage recursively if needed
  299. template = getattr(self.vm, 'template', None)
  300. if template and template.storage is None:
  301. template.storage = Storage(template)
  302. if volume_config['source'] is None:
  303. self._update_volume_config_source(name, volume_config)
  304. else:
  305. # if source is already specified, pool needs to be too
  306. pool = self.vm.app.get_pool(volume_config['pool'])
  307. volume_config['source'] = pool.volumes[volume_config['source']]
  308. # if pool still unknown, load default
  309. if 'pool' not in volume_config:
  310. volume_config['pool'] = \
  311. getattr(self.vm.app, 'default_pool_' + name)
  312. pool = self.vm.app.get_pool(volume_config['pool'])
  313. if 'internal' in volume_config:
  314. # migrate old config
  315. del volume_config['internal']
  316. volume = pool.init_volume(self.vm, volume_config)
  317. self.vm.volumes[name] = volume
  318. return volume
  319. def attach(self, volume, rw=False):
  320. ''' Attach a volume to the domain '''
  321. assert self.vm.is_running()
  322. if self._is_already_attached(volume):
  323. self.vm.log.info("{!r} already attached".format(volume))
  324. return
  325. try:
  326. frontend = self.unused_frontend()
  327. except IndexError:
  328. raise StoragePoolException("No unused frontend found")
  329. disk = lxml.etree.Element("disk")
  330. disk.set('type', 'block')
  331. disk.set('device', 'disk')
  332. lxml.etree.SubElement(disk, 'driver').set('name', 'phy')
  333. lxml.etree.SubElement(disk, 'source').set('dev', '/dev/%s' % volume.vid)
  334. lxml.etree.SubElement(disk, 'target').set('dev', frontend)
  335. if not rw:
  336. lxml.etree.SubElement(disk, 'readonly')
  337. if volume.domain is not None:
  338. lxml.etree.SubElement(disk, 'backenddomain').set(
  339. 'name', volume.domain.name)
  340. xml_string = lxml.etree.tostring(disk, encoding='utf-8')
  341. self.vm.libvirt_domain.attachDevice(xml_string)
  342. # trigger watches to update device status
  343. # FIXME: this should be removed once libvirt will report such
  344. # events itself
  345. # self.vm.untrusted_qdb.write('/qubes-block-devices', '')
  346. # ← do we need this?
  347. def _is_already_attached(self, volume):
  348. ''' Checks if the given volume is already attached '''
  349. parsed_xml = lxml.etree.fromstring(self.vm.libvirt_domain.XMLDesc())
  350. disk_sources = parsed_xml.xpath("//domain/devices/disk/source")
  351. for source in disk_sources:
  352. if source.get('dev') == '/dev/%s' % volume.vid:
  353. return True
  354. return False
  355. def detach(self, volume):
  356. ''' Detach a volume from domain '''
  357. parsed_xml = lxml.etree.fromstring(self.vm.libvirt_domain.XMLDesc())
  358. disks = parsed_xml.xpath("//domain/devices/disk")
  359. for disk in disks:
  360. source = disk.xpath('source')[0]
  361. if source.get('dev') == '/dev/%s' % volume.vid:
  362. disk_xml = lxml.etree.tostring(disk, encoding='utf-8')
  363. self.vm.libvirt_domain.detachDevice(disk_xml)
  364. return
  365. raise StoragePoolException('Volume {!r} is not attached'.format(volume))
  366. @property
  367. def kernels_dir(self):
  368. '''Directory where kernel resides.
  369. If :py:attr:`self.vm.kernel` is :py:obj:`None`, the this points inside
  370. :py:attr:`self.vm.dir_path`
  371. '''
  372. assert 'kernel' in self.vm.volumes, "VM has no kernel volume"
  373. return self.vm.volumes['kernel'].kernels_dir
  374. def get_disk_utilization(self):
  375. ''' Returns summed up disk utilization for all domain volumes '''
  376. result = 0
  377. for volume in self.vm.volumes.values():
  378. result += volume.usage
  379. return result
  380. @asyncio.coroutine
  381. def resize(self, volume, size):
  382. ''' Resizes volume a read-writable volume '''
  383. if isinstance(volume, str):
  384. volume = self.vm.volumes[volume]
  385. ret = volume.resize(size)
  386. if asyncio.iscoroutine(ret):
  387. yield from ret
  388. if self.vm.is_running():
  389. yield from self.vm.run_service_for_stdio('qubes.ResizeDisk',
  390. input=volume.name.encode(),
  391. user='root')
  392. @asyncio.coroutine
  393. def create(self):
  394. ''' Creates volumes on disk '''
  395. old_umask = os.umask(0o002)
  396. coros = []
  397. for volume in self.vm.volumes.values():
  398. # launch the operation, if it's asynchronous, then append to wait
  399. # for them at the end
  400. ret = volume.create()
  401. if asyncio.iscoroutine(ret):
  402. coros.append(ret)
  403. if coros:
  404. yield from asyncio.wait(coros)
  405. os.umask(old_umask)
  406. @asyncio.coroutine
  407. def clone_volume(self, src_vm, name):
  408. ''' Clone single volume from the specified vm
  409. :param QubesVM src_vm: source VM
  410. :param str name: name of volume to clone ('root', 'private' etc)
  411. :return cloned volume object
  412. '''
  413. config = self.vm.volume_config[name]
  414. dst_pool = self.vm.app.get_pool(config['pool'])
  415. dst = dst_pool.init_volume(self.vm, config)
  416. src_volume = src_vm.volumes[name]
  417. msg = "Importing volume {!s} from vm {!s}"
  418. self.vm.log.info(msg.format(src_volume.name, src_vm.name))
  419. # First create the destination volume
  420. create_op_ret = dst.create()
  421. # clone/import functions may be either synchronous or asynchronous
  422. # in the later case, we need to wait for them to finish
  423. if asyncio.iscoroutine(create_op_ret):
  424. yield from create_op_ret
  425. # Then import data from source volume
  426. clone_op_ret = dst.import_volume(src_volume)
  427. # clone/import functions may be either synchronous or asynchronous
  428. # in the later case, we need to wait for them to finish
  429. if asyncio.iscoroutine(clone_op_ret):
  430. yield from clone_op_ret
  431. self.vm.volumes[name] = dst
  432. return self.vm.volumes[name]
  433. @asyncio.coroutine
  434. def clone(self, src_vm):
  435. ''' Clone volumes from the specified vm '''
  436. self.vm.volumes = {}
  437. with VmCreationManager(self.vm):
  438. yield from asyncio.wait([self.clone_volume(src_vm, vol_name)
  439. for vol_name in self.vm.volume_config.keys()])
  440. @property
  441. def outdated_volumes(self):
  442. ''' Returns a list of outdated volumes '''
  443. result = []
  444. if self.vm.is_halted():
  445. return result
  446. volumes = self.vm.volumes
  447. for volume in volumes.values():
  448. if volume.is_outdated():
  449. result += [volume]
  450. return result
  451. @asyncio.coroutine
  452. def verify(self):
  453. '''Verify that the storage is sane.
  454. On success, returns normally. On failure, raises exception.
  455. '''
  456. if not os.path.exists(self.vm.dir_path):
  457. raise qubes.exc.QubesVMError(
  458. self.vm,
  459. 'VM directory does not exist: {}'.format(self.vm.dir_path))
  460. futures = []
  461. for volume in self.vm.volumes.values():
  462. ret = volume.verify()
  463. if asyncio.iscoroutine(ret):
  464. futures.append(ret)
  465. if futures:
  466. yield from asyncio.wait(futures)
  467. self.vm.fire_event('domain-verify-files')
  468. return True
  469. @asyncio.coroutine
  470. def remove(self):
  471. ''' Remove all the volumes.
  472. Errors on removal are catched and logged.
  473. '''
  474. futures = []
  475. for name, volume in self.vm.volumes.items():
  476. self.log.info('Removing volume %s: %s' % (name, volume.vid))
  477. try:
  478. ret = volume.remove()
  479. if asyncio.iscoroutine(ret):
  480. futures.append(ret)
  481. except (IOError, OSError) as e:
  482. self.vm.log.exception("Failed to remove volume %s", name, e)
  483. if futures:
  484. try:
  485. yield from asyncio.wait(futures)
  486. except (IOError, OSError) as e:
  487. self.vm.log.exception("Failed to remove some volume", e)
  488. @asyncio.coroutine
  489. def start(self):
  490. ''' Execute the start method on each pool '''
  491. futures = []
  492. for volume in self.vm.volumes.values():
  493. ret = volume.start()
  494. if asyncio.iscoroutine(ret):
  495. futures.append(ret)
  496. if futures:
  497. yield from asyncio.wait(futures)
  498. @asyncio.coroutine
  499. def stop(self):
  500. ''' Execute the start method on each pool '''
  501. futures = []
  502. for volume in self.vm.volumes.values():
  503. ret = volume.stop()
  504. if asyncio.iscoroutine(ret):
  505. futures.append(ret)
  506. if futures:
  507. yield from asyncio.wait(futures)
  508. def unused_frontend(self):
  509. ''' Find an unused device name '''
  510. unused_frontends = self.AVAILABLE_FRONTENDS.difference(
  511. self.used_frontends)
  512. return sorted(unused_frontends)[0]
  513. @property
  514. def used_frontends(self):
  515. ''' Used device names '''
  516. xml = self.vm.libvirt_domain.XMLDesc()
  517. parsed_xml = lxml.etree.fromstring(xml)
  518. return set([target.get('dev', None)
  519. for target in parsed_xml.xpath(
  520. "//domain/devices/disk/target")])
  521. def export(self, volume):
  522. ''' Helper function to export volume (pool.export(volume))'''
  523. assert isinstance(volume, (Volume, str)), \
  524. "You need to pass a Volume or pool name as str"
  525. if isinstance(volume, Volume):
  526. return volume.export()
  527. return self.vm.volumes[volume].export()
  528. def import_data(self, volume):
  529. ''' Helper function to import volume data (pool.import_data(volume))'''
  530. assert isinstance(volume, (Volume, str)), \
  531. "You need to pass a Volume or pool name as str"
  532. if isinstance(volume, Volume):
  533. return volume.import_data()
  534. return self.vm.volumes[volume].import_data()
  535. def import_data_end(self, volume, success):
  536. ''' Helper function to finish/cleanup data import
  537. (pool.import_data_end( volume))'''
  538. assert isinstance(volume, (Volume, str)), \
  539. "You need to pass a Volume or pool name as str"
  540. if isinstance(volume, Volume):
  541. return volume.import_data_end(success=success)
  542. return self.vm.volumes[volume].import_data_end(success=success)
  543. class VolumesCollection(object):
  544. '''Convenient collection wrapper for pool.get_volume and
  545. pool.list_volumes
  546. '''
  547. def __init__(self, pool):
  548. self._pool = pool
  549. def __getitem__(self, item):
  550. ''' Get a single volume with given Volume ID.
  551. You can also a Volume instance to get the same Volume or KeyError if
  552. Volume no longer exists.
  553. :param item: a Volume ID (str) or a Volume instance
  554. '''
  555. if isinstance(item, Volume):
  556. if item.pool == self._pool:
  557. return self[item.vid]
  558. else:
  559. raise KeyError(item)
  560. try:
  561. return self._pool.get_volume(item)
  562. except NotImplementedError:
  563. for vol in self:
  564. if vol.vid == item:
  565. return vol
  566. # if list_volumes is not implemented too, it will raise
  567. # NotImplementedError again earlier
  568. raise KeyError(item)
  569. def __iter__(self):
  570. ''' Get iterator over pool's volumes '''
  571. return iter(self._pool.list_volumes())
  572. def __contains__(self, item):
  573. ''' Check if given volume (either Volume ID or Volume instance) is
  574. present in the pool
  575. '''
  576. try:
  577. return self[item] is not None
  578. except KeyError:
  579. return False
  580. def keys(self):
  581. ''' Return list of volume IDs '''
  582. return [vol.vid for vol in self]
  583. def values(self):
  584. ''' Return list of Volumes'''
  585. return [vol for vol in self]
  586. class Pool(object):
  587. ''' A Pool is used to manage different kind of volumes (File
  588. based/LVM/Btrfs/...).
  589. 3rd Parties providing own storage implementations will need to extend
  590. this class.
  591. ''' # pylint: disable=unused-argument
  592. private_img_size = qubes.config.defaults['private_img_size']
  593. root_img_size = qubes.config.defaults['root_img_size']
  594. def __init__(self, name, revisions_to_keep=1, **kwargs):
  595. super(Pool, self).__init__(**kwargs)
  596. self._volumes_collection = VolumesCollection(self)
  597. self.name = name
  598. self.revisions_to_keep = revisions_to_keep
  599. kwargs['name'] = self.name
  600. def __eq__(self, other):
  601. if isinstance(other, Pool):
  602. return self.name == other.name
  603. elif isinstance(other, str):
  604. return self.name == other
  605. return NotImplemented
  606. def __neq__(self, other):
  607. return not self.__eq__(other)
  608. def __str__(self):
  609. return self.name
  610. def __hash__(self):
  611. return hash(self.name)
  612. def __xml__(self):
  613. config = _sanitize_config(self.config)
  614. return lxml.etree.Element('pool', **config)
  615. @property
  616. def config(self):
  617. ''' Returns the pool config to be written to qubes.xml '''
  618. raise self._not_implemented("config")
  619. def destroy(self):
  620. ''' Called when removing the pool. Use this for implementation specific
  621. clean up.
  622. '''
  623. raise self._not_implemented("destroy")
  624. def init_volume(self, vm, volume_config):
  625. ''' Initialize a :py:class:`qubes.storage.Volume` from `volume_config`.
  626. '''
  627. raise self._not_implemented("init_volume")
  628. def setup(self):
  629. ''' Called when adding a pool to the system. Use this for implementation
  630. specific set up.
  631. '''
  632. raise self._not_implemented("setup")
  633. @property
  634. def volumes(self):
  635. ''' Return a collection of volumes managed by this pool '''
  636. return self._volumes_collection
  637. def list_volumes(self):
  638. ''' Return a list of volumes managed by this pool '''
  639. raise self._not_implemented("list_volumes")
  640. def get_volume(self, vid):
  641. ''' Return a volume with *vid* from this pool
  642. :raise KeyError: if no volume is found
  643. '''
  644. raise self._not_implemented("get_volume")
  645. def _not_implemented(self, method_name):
  646. ''' Helper for emitting helpful `NotImplementedError` exceptions '''
  647. msg = "Pool driver {!s} has {!s}() not implemented"
  648. msg = msg.format(str(self.__class__.__name__), method_name)
  649. return NotImplementedError(msg)
  650. def _sanitize_config(config):
  651. ''' Helper function to convert types to appropriate strings
  652. ''' # FIXME: find another solution for serializing basic types
  653. result = {}
  654. for key, value in config.items():
  655. if isinstance(value, bool):
  656. if value:
  657. result[key] = 'True'
  658. else:
  659. result[key] = str(value)
  660. return result
  661. def pool_drivers():
  662. """ Return a list of EntryPoints names """
  663. return [ep.name
  664. for ep in pkg_resources.iter_entry_points(STORAGE_ENTRY_POINT)]
  665. def driver_parameters(name):
  666. ''' Get __init__ parameters from a driver with out `self` & `name`. '''
  667. init_function = qubes.utils.get_entry_point_one(
  668. qubes.storage.STORAGE_ENTRY_POINT, name).__init__
  669. signature = inspect.signature(init_function)
  670. params = signature.parameters.keys()
  671. ignored_params = ['self', 'name', 'kwargs']
  672. return [p for p in params if p not in ignored_params]
  673. def isodate(seconds=time.time()):
  674. ''' Helper method which returns an iso date '''
  675. return datetime.utcfromtimestamp(seconds).isoformat("T")
  676. class VmCreationManager(object):
  677. ''' A `ContextManager` which cleans up if volume creation fails.
  678. ''' # pylint: disable=too-few-public-methods
  679. def __init__(self, vm):
  680. self.vm = vm
  681. def __enter__(self):
  682. pass
  683. def __exit__(self, type, value, tb): # pylint: disable=redefined-builtin
  684. if type is not None and value is not None and tb is not None:
  685. for volume in self.vm.volumes.values():
  686. try:
  687. volume.remove()
  688. except Exception: # pylint: disable=broad-except
  689. pass
  690. os.rmdir(self.vm.dir_path)