__init__.py 25 KB

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