__init__.py 27 KB

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