__init__.py 28 KB

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