__init__.py 25 KB

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