__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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 os
  26. import os.path
  27. import string # pylint: disable=deprecated-module
  28. import time
  29. from datetime import datetime
  30. import lxml.etree
  31. import pkg_resources
  32. import qubes
  33. import qubes.exc
  34. import qubes.utils
  35. STORAGE_ENTRY_POINT = 'qubes.storage'
  36. class StoragePoolException(qubes.exc.QubesException):
  37. ''' A general storage exception '''
  38. pass
  39. class BlockDevice(object):
  40. ''' Represents a storage block device. '''
  41. # pylint: disable=too-few-public-methods
  42. def __init__(self, path, name, script=None, rw=True, domain=None,
  43. devtype='disk'):
  44. assert name, 'Missing device name'
  45. assert path, 'Missing device path'
  46. self.path = path
  47. self.name = name
  48. self.rw = rw
  49. self.script = script
  50. self.domain = domain
  51. self.devtype = devtype
  52. class Volume(object):
  53. ''' Encapsulates all data about a volume for serialization to qubes.xml and
  54. libvirt config.
  55. Keep in mind!
  56. volatile = not snap_on_start and not save_on_stop
  57. snapshot = snap_on_start and not save_on_stop
  58. origin = not snap_on_start and save_on_stop
  59. origin_snapshot = snap_on_start and save_on_stop
  60. '''
  61. devtype = 'disk'
  62. domain = None
  63. path = None
  64. script = None
  65. usage = 0
  66. def __init__(self, name, pool, vid, internal=False, removable=False,
  67. revisions_to_keep=0, rw=False, save_on_stop=False, size=0,
  68. snap_on_start=False, source=None, **kwargs):
  69. ''' Initialize a volume.
  70. :param str name: The domain name
  71. :param str pool: The pool name
  72. :param str vid: Volume identifier needs to be unique in pool
  73. :param bool internal: If `True` volume is hidden when qvm-block ls
  74. is used
  75. :param bool removable: If `True` volume can be detached from vm at
  76. run time
  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 start
  80. :param bool save_on_stop: Write changes to disk in vm.stop()
  81. :param str source: Vid of other volume in same pool
  82. :param str/int size: Size of the volume
  83. '''
  84. super(Volume, self).__init__(**kwargs)
  85. self.name = str(name)
  86. self.pool = str(pool)
  87. self.internal = internal
  88. self.removable = removable
  89. self.revisions_to_keep = int(revisions_to_keep)
  90. self.rw = rw
  91. self.save_on_stop = save_on_stop
  92. self._size = int(size)
  93. self.snap_on_start = snap_on_start
  94. self.source = source
  95. self.vid = vid
  96. def __eq__(self, other):
  97. return other.pool == self.pool and other.vid == self.vid
  98. def __hash__(self):
  99. return hash('%s:%s' % (self.pool, self.vid))
  100. def __neq__(self, other):
  101. return not self.__eq__(other)
  102. def __repr__(self):
  103. return '{!r}'.format(self.pool + ':' + self.vid)
  104. def __str__(self):
  105. return str(self.vid)
  106. def __xml__(self):
  107. config = _sanitize_config(self.config)
  108. return lxml.etree.Element('volume', **config)
  109. def block_device(self):
  110. ''' Return :py:class:`BlockDevice` for serialization in
  111. the libvirt XML template as <disk>.
  112. '''
  113. return BlockDevice(self.path, self.name, self.script,
  114. self.rw, self.domain, self.devtype)
  115. @property
  116. def revisions(self):
  117. ''' Returns a `dict` containing revision identifiers and paths '''
  118. msg = "{!s} has revisions not implemented".format(self.__class__)
  119. raise NotImplementedError(msg)
  120. @property
  121. def size(self):
  122. return self._size
  123. @size.setter
  124. def size(self, size):
  125. # pylint: disable=attribute-defined-outside-init
  126. self._size = int(size)
  127. @property
  128. def config(self):
  129. ''' return config data for serialization to qubes.xml '''
  130. result = {'name': self.name, 'pool': self.pool, 'vid': self.vid, }
  131. if self.internal:
  132. result['internal'] = self.internal
  133. if self.removable:
  134. result['removable'] = self.removable
  135. if self.revisions_to_keep:
  136. result['revisions_to_keep'] = self.revisions_to_keep
  137. if self.rw:
  138. result['rw'] = self.rw
  139. if self.save_on_stop:
  140. result['save_on_stop'] = self.save_on_stop
  141. if self.size:
  142. result['size'] = self.size
  143. if self.snap_on_start:
  144. result['snap_on_start'] = self.snap_on_start
  145. if self.source:
  146. result['source'] = self.source
  147. return result
  148. class Storage(object):
  149. ''' Class for handling VM virtual disks.
  150. This is base class for all other implementations, mostly with Xen on Linux
  151. in mind.
  152. '''
  153. AVAILABLE_FRONTENDS = set(['xvd' + c for c in string.ascii_lowercase])
  154. def __init__(self, vm):
  155. #: Domain for which we manage storage
  156. self.vm = vm
  157. self.log = self.vm.log
  158. #: Additional drive (currently used only by HVM)
  159. self.drive = None
  160. self.pools = {}
  161. if hasattr(vm, 'volume_config'):
  162. for name, conf in self.vm.volume_config.items():
  163. if 'volume_type' in conf:
  164. conf = self._migrate_config(conf)
  165. self.init_volume(name, conf)
  166. def init_volume(self, name, volume_config):
  167. ''' Initialize Volume instance attached to this domain '''
  168. assert 'pool' in volume_config, "Pool missing in volume_config" % str(
  169. volume_config)
  170. if 'name' not in volume_config:
  171. volume_config['name'] = name
  172. pool = self.vm.app.get_pool(volume_config['pool'])
  173. volume = pool.init_volume(self.vm, volume_config)
  174. self.vm.volumes[name] = volume
  175. self.pools[name] = pool
  176. return volume
  177. def _migrate_config(self, conf):
  178. ''' Migrates from the old config style to new
  179. ''' # FIXME: Remove this compatibility hack
  180. assert 'volume_type' in conf
  181. _type = conf['volume_type']
  182. old_volume_types = [
  183. 'read-write', 'read-only', 'origin', 'snapshot', 'volatile'
  184. ]
  185. msg = "Volume {!s} has unknown type {!s}".format(conf['name'], _type)
  186. assert conf['volume_type'] in old_volume_types, msg
  187. if _type == 'origin':
  188. conf['rw'] = True
  189. conf['source'] = None
  190. conf['save_on_stop'] = True
  191. conf['revisions_to_keep'] = 1
  192. elif _type == 'snapshot':
  193. conf['rw'] = False
  194. if conf['pool'] == 'default':
  195. template_vid = os.path.join('vm-templates',
  196. self.vm.template.name, conf['name'])
  197. elif conf['pool'] == 'qubes_dom0':
  198. template_vid = os.path.join(
  199. 'qubes_dom0', self.vm.template.name + '-' + conf['name'])
  200. conf['source'] = template_vid
  201. conf['snap_on_start'] = True
  202. elif _type == 'read-write':
  203. conf['rw'] = True
  204. conf['save_on_stop'] = True
  205. conf['revisions_to_keep'] = 0
  206. elif _type == 'read-only':
  207. conf['rw'] = False
  208. conf['snap_on_start'] = True
  209. conf['save_on_stop'] = False
  210. conf['revisions_to_keep'] = 0
  211. elif _type == 'volatile':
  212. conf['snap_on_start'] = False
  213. conf['save_on_stop'] = False
  214. conf['revisions_to_keep'] = 0
  215. del conf['volume_type']
  216. return conf
  217. def attach(self, volume, rw=False):
  218. ''' Attach a volume to the domain '''
  219. assert self.vm.is_running()
  220. if self._is_already_attached(volume):
  221. self.vm.log.info("{!r} already attached".format(volume))
  222. return
  223. try:
  224. frontend = self.unused_frontend()
  225. except IndexError:
  226. raise StoragePoolException("No unused frontend found")
  227. disk = lxml.etree.Element("disk")
  228. disk.set('type', 'block')
  229. disk.set('device', 'disk')
  230. lxml.etree.SubElement(disk, 'driver').set('name', 'phy')
  231. lxml.etree.SubElement(disk, 'source').set('dev', '/dev/%s' % volume.vid)
  232. lxml.etree.SubElement(disk, 'target').set('dev', frontend)
  233. if not rw:
  234. lxml.etree.SubElement(disk, 'readonly')
  235. if volume.domain is not None:
  236. lxml.etree.SubElement(disk, 'backenddomain').set(
  237. 'name', volume.domain.name)
  238. xml_string = lxml.etree.tostring(disk, encoding='utf-8')
  239. self.vm.libvirt_domain.attachDevice(xml_string)
  240. # trigger watches to update device status
  241. # FIXME: this should be removed once libvirt will report such
  242. # events itself
  243. # self.vm.qdb.write('/qubes-block-devices', '') ← do we need this?
  244. def _is_already_attached(self, volume):
  245. ''' Checks if the given volume is already attached '''
  246. parsed_xml = lxml.etree.fromstring(self.vm.libvirt_domain.XMLDesc())
  247. disk_sources = parsed_xml.xpath("//domain/devices/disk/source")
  248. for source in disk_sources:
  249. if source.get('dev') == '/dev/%s' % volume.vid:
  250. return True
  251. return False
  252. def detach(self, volume):
  253. ''' Detach a volume from domain '''
  254. parsed_xml = lxml.etree.fromstring(self.vm.libvirt_domain.XMLDesc())
  255. disks = parsed_xml.xpath("//domain/devices/disk")
  256. for disk in disks:
  257. source = disk.xpath('source')[0]
  258. if source.get('dev') == '/dev/%s' % volume.vid:
  259. disk_xml = lxml.etree.tostring(disk, encoding='utf-8')
  260. self.vm.libvirt_domain.detachDevice(disk_xml)
  261. return
  262. raise StoragePoolException('Volume {!r} is not attached'.format(volume))
  263. @property
  264. def kernels_dir(self):
  265. '''Directory where kernel resides.
  266. If :py:attr:`self.vm.kernel` is :py:obj:`None`, the this points inside
  267. :py:attr:`self.vm.dir_path`
  268. '''
  269. assert 'kernel' in self.vm.volumes, "VM has no kernel volume"
  270. return self.vm.volumes['kernel'].kernels_dir
  271. def get_disk_utilization(self):
  272. ''' Returns summed up disk utilization for all domain volumes '''
  273. result = 0
  274. for volume in self.vm.volumes.values():
  275. result += volume.usage
  276. return result
  277. def resize(self, volume, size):
  278. ''' Resizes volume a read-writable volume '''
  279. if isinstance(volume, str):
  280. volume = self.vm.volumes[volume]
  281. self.get_pool(volume).resize(volume, size)
  282. if self.vm.is_running():
  283. self.vm.run_service('qubes.ResizeDisk', input=volume.name.encode(),
  284. user='root', wait=True)
  285. def create(self):
  286. ''' Creates volumes on disk '''
  287. old_umask = os.umask(0o002)
  288. for volume in self.vm.volumes.values():
  289. self.get_pool(volume).create(volume)
  290. os.umask(old_umask)
  291. def clone(self, src_vm):
  292. ''' Clone volumes from the specified vm '''
  293. src_path = src_vm.dir_path
  294. msg = "Source path {!s} does not exist".format(src_path)
  295. assert os.path.exists(src_path), msg
  296. dst_path = self.vm.dir_path
  297. msg = "Destination {!s} already exists".format(dst_path)
  298. assert not os.path.exists(dst_path), msg
  299. os.mkdir(dst_path)
  300. self.vm.volumes = {}
  301. with VmCreationManager(self.vm):
  302. for name, config in self.vm.volume_config.items():
  303. dst_pool = self.get_pool(config['pool'])
  304. dst = dst_pool.init_volume(self.vm, config)
  305. src_volume = src_vm.volumes[name]
  306. src_pool = self.vm.app.get_pool(src_volume.pool)
  307. if dst_pool == src_pool:
  308. msg = "Cloning volume {!s} from vm {!s}"
  309. self.vm.log.info(msg.format(src_volume.name, src_vm.name))
  310. volume = dst_pool.clone(src_volume, dst)
  311. else:
  312. msg = "Importing volume {!s} from vm {!s}"
  313. self.vm.log.info(msg.format(src_volume.name, src_vm.name))
  314. volume = dst_pool.import_volume(dst_pool, dst, src_pool,
  315. src_volume)
  316. assert volume, "%s.clone() returned '%s'" % (
  317. dst_pool.__class__.__name__, volume)
  318. self.vm.volumes[name] = volume
  319. msg = "Cloning directory: {!s} to {!s}"
  320. msg = msg.format(src_path, dst_path)
  321. self.log.info(msg)
  322. @property
  323. def outdated_volumes(self):
  324. ''' Returns a list of outdated volumes '''
  325. result = []
  326. if self.vm.is_halted():
  327. return result
  328. volumes = self.vm.volumes
  329. for volume in volumes.values():
  330. pool = self.get_pool(volume)
  331. if pool.is_outdated(volume):
  332. result += [volume]
  333. return result
  334. def rename(self, old_name, new_name):
  335. ''' Notify the pools that the domain was renamed '''
  336. volumes = self.vm.volumes
  337. vm = self.vm
  338. old_dir_path = os.path.join(os.path.dirname(vm.dir_path), old_name)
  339. new_dir_path = os.path.join(os.path.dirname(vm.dir_path), new_name)
  340. os.rename(old_dir_path, new_dir_path)
  341. for name, volume in volumes.items():
  342. pool = self.get_pool(volume)
  343. volumes[name] = pool.rename(volume, old_name, new_name)
  344. def verify(self):
  345. '''Verify that the storage is sane.
  346. On success, returns normally. On failure, raises exception.
  347. '''
  348. if not os.path.exists(self.vm.dir_path):
  349. raise qubes.exc.QubesVMError(
  350. self.vm,
  351. 'VM directory does not exist: {}'.format(self.vm.dir_path))
  352. for volume in self.vm.volumes.values():
  353. self.get_pool(volume).verify(volume)
  354. self.vm.fire_event('domain-verify-files')
  355. return True
  356. def remove(self):
  357. ''' Remove all the volumes.
  358. Errors on removal are catched and logged.
  359. '''
  360. for name, volume in self.vm.volumes.items():
  361. self.log.info('Removing volume %s: %s' % (name, volume.vid))
  362. try:
  363. self.get_pool(volume).remove(volume)
  364. except (IOError, OSError) as e:
  365. self.vm.log.exception("Failed to remove volume %s", name, e)
  366. def start(self):
  367. ''' Execute the start method on each pool '''
  368. for volume in self.vm.volumes.values():
  369. pool = self.get_pool(volume)
  370. volume = pool.start(volume)
  371. def stop(self):
  372. ''' Execute the start method on each pool '''
  373. for volume in self.vm.volumes.values():
  374. self.get_pool(volume).stop(volume)
  375. def get_pool(self, volume):
  376. ''' Helper function '''
  377. assert isinstance(volume, (Volume, str)), \
  378. "You need to pass a Volume or pool name as str"
  379. if isinstance(volume, Volume):
  380. return self.pools[volume.name]
  381. return self.vm.app.pools[volume]
  382. def commit(self):
  383. ''' Makes changes to an 'origin' volume persistent '''
  384. for volume in self.vm.volumes.values():
  385. if volume.save_on_stop:
  386. self.get_pool(volume).commit(volume)
  387. def unused_frontend(self):
  388. ''' Find an unused device name '''
  389. unused_frontends = self.AVAILABLE_FRONTENDS.difference(
  390. self.used_frontends)
  391. return sorted(unused_frontends)[0]
  392. @property
  393. def used_frontends(self):
  394. ''' Used device names '''
  395. xml = self.vm.libvirt_domain.XMLDesc()
  396. parsed_xml = lxml.etree.fromstring(xml)
  397. return set([target.get('dev', None)
  398. for target in parsed_xml.xpath(
  399. "//domain/devices/disk/target")])
  400. def export(self, volume):
  401. ''' Helper function to export volume (pool.export(volume))'''
  402. assert isinstance(volume, (Volume, str)), \
  403. "You need to pass a Volume or pool name as str"
  404. if isinstance(volume, Volume):
  405. return self.pools[volume.name].export(volume)
  406. return self.pools[volume].export(self.vm.volumes[volume])
  407. class Pool(object):
  408. ''' A Pool is used to manage different kind of volumes (File
  409. based/LVM/Btrfs/...).
  410. 3rd Parties providing own storage implementations will need to extend
  411. this class.
  412. ''' # pylint: disable=unused-argument
  413. private_img_size = qubes.config.defaults['private_img_size']
  414. root_img_size = qubes.config.defaults['root_img_size']
  415. def __init__(self, name, revisions_to_keep=1, **kwargs):
  416. super(Pool, self).__init__(**kwargs)
  417. self.name = name
  418. self.revisions_to_keep = revisions_to_keep
  419. kwargs['name'] = self.name
  420. def __eq__(self, other):
  421. return self.name == other.name
  422. def __neq__(self, other):
  423. return not self.__eq__(other)
  424. def __str__(self):
  425. return self.name
  426. def __xml__(self):
  427. config = _sanitize_config(self.config)
  428. return lxml.etree.Element('pool', **config)
  429. def create(self, volume):
  430. ''' Create the given volume on disk or copy from provided
  431. `source_volume`.
  432. '''
  433. raise self._not_implemented("create")
  434. def commit(self, volume): # pylint: disable=no-self-use
  435. ''' Write the snapshot to disk '''
  436. msg = "Got volume_type {!s} when expected 'snap'"
  437. msg = msg.format(volume.volume_type)
  438. assert volume.volume_type == 'snap', msg
  439. @property
  440. def config(self):
  441. ''' Returns the pool config to be written to qubes.xml '''
  442. raise self._not_implemented("config")
  443. def clone(self, source, target):
  444. ''' Clone volume '''
  445. raise self._not_implemented("clone")
  446. def destroy(self):
  447. ''' Called when removing the pool. Use this for implementation specific
  448. clean up.
  449. '''
  450. raise self._not_implemented("destroy")
  451. def export(self, volume):
  452. ''' Returns an object that can be `open()`. '''
  453. raise self._not_implemented("export")
  454. def import_volume(self, dst_pool, dst_volume, src_pool, src_volume):
  455. ''' Imports data to a volume in this pool '''
  456. raise self._not_implemented("import_volume")
  457. def init_volume(self, vm, volume_config):
  458. ''' Initialize a :py:class:`qubes.storage.Volume` from `volume_config`.
  459. '''
  460. raise self._not_implemented("init_volume")
  461. def is_dirty(self, volume):
  462. ''' Return `True` if volume was not properly shutdown and commited '''
  463. raise self._not_implemented("is_dirty")
  464. def is_outdated(self, volume):
  465. ''' Returns `True` if the currently used `volume.source` of a snapshot
  466. volume is outdated.
  467. '''
  468. raise self._not_implemented("is_outdated")
  469. def recover(self, volume):
  470. ''' Try to recover a :py:class:`Volume` or :py:class:`SnapVolume` '''
  471. raise self._not_implemented("recover")
  472. def remove(self, volume):
  473. ''' Remove volume'''
  474. raise self._not_implemented("remove")
  475. def rename(self, volume, old_name, new_name):
  476. ''' Called when the domain changes its name '''
  477. raise self._not_implemented("rename")
  478. def reset(self, volume):
  479. ''' Drop and recreate volume without copying it's content from source.
  480. '''
  481. raise self._not_implemented("reset")
  482. def resize(self, volume, size):
  483. ''' Expands volume, throws
  484. :py:class:`qubes.storage.StoragePoolException` if
  485. given size is less than current_size
  486. '''
  487. raise self._not_implemented("resize")
  488. def revert(self, volume, revision=None):
  489. ''' Revert volume to previous revision '''
  490. raise self._not_implemented("revert")
  491. def setup(self):
  492. ''' Called when adding a pool to the system. Use this for implementation
  493. specific set up.
  494. '''
  495. raise self._not_implemented("setup")
  496. def start(self, volume): # pylint: disable=no-self-use
  497. ''' Do what ever is needed on start '''
  498. raise self._not_implemented("start")
  499. def stop(self, volume): # pylint: disable=no-self-use
  500. ''' Do what ever is needed on stop'''
  501. def verify(self, volume):
  502. ''' Verifies the volume. '''
  503. raise self._not_implemented("verify")
  504. @property
  505. def volumes(self):
  506. ''' Return a list of volumes managed by this pool '''
  507. raise self._not_implemented("volumes")
  508. def _not_implemented(self, method_name):
  509. ''' Helper for emitting helpful `NotImplementedError` exceptions '''
  510. msg = "Pool driver {!s} has {!s}() not implemented"
  511. msg = msg.format(str(self.__class__.__name__), method_name)
  512. return NotImplementedError(msg)
  513. def _sanitize_config(config):
  514. ''' Helper function to convert types to appropriate strings
  515. ''' # FIXME: find another solution for serializing basic types
  516. result = {}
  517. for key, value in config.items():
  518. if isinstance(value, bool):
  519. if value:
  520. result[key] = 'True'
  521. else:
  522. result[key] = str(value)
  523. return result
  524. def pool_drivers():
  525. """ Return a list of EntryPoints names """
  526. return [ep.name
  527. for ep in pkg_resources.iter_entry_points(STORAGE_ENTRY_POINT)]
  528. def driver_parameters(name):
  529. ''' Get __init__ parameters from a driver with out `self` & `name`. '''
  530. init_function = qubes.utils.get_entry_point_one(
  531. qubes.storage.STORAGE_ENTRY_POINT, name).__init__
  532. params = init_function.func_code.co_varnames
  533. ignored_params = ['self', 'name']
  534. return [p for p in params if p not in ignored_params]
  535. def isodate(seconds=time.time()):
  536. ''' Helper method which returns an iso date '''
  537. return datetime.utcfromtimestamp(seconds).isoformat("T")
  538. class VmCreationManager(object):
  539. ''' A `ContextManager` which cleans up if volume creation fails.
  540. ''' # pylint: disable=too-few-public-methods
  541. def __init__(self, vm):
  542. self.vm = vm
  543. def __enter__(self):
  544. pass
  545. def __exit__(self, type, value, tb): # pylint: disable=redefined-builtin
  546. if type is not None and value is not None and tb is not None:
  547. for volume in self.vm.volumes.values():
  548. try:
  549. pool = self.vm.storage.get_pool(volume)
  550. pool.remove(volume)
  551. except Exception: # pylint: disable=broad-except
  552. pass
  553. os.rmdir(self.vm.dir_path)