__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. @asyncio.coroutine
  359. def verify(self):
  360. '''Verify that the storage is sane.
  361. On success, returns normally. On failure, raises exception.
  362. '''
  363. if not os.path.exists(self.vm.dir_path):
  364. raise qubes.exc.QubesVMError(
  365. self.vm,
  366. 'VM directory does not exist: {}'.format(self.vm.dir_path))
  367. futures = []
  368. for volume in self.vm.volumes.values():
  369. ret = self.get_pool(volume).verify(volume)
  370. if asyncio.iscoroutine(ret):
  371. futures.append(ret)
  372. if futures:
  373. yield from asyncio.wait(futures)
  374. self.vm.fire_event('domain-verify-files')
  375. return True
  376. @asyncio.coroutine
  377. def remove(self):
  378. ''' Remove all the volumes.
  379. Errors on removal are catched and logged.
  380. '''
  381. futures = []
  382. for name, volume in self.vm.volumes.items():
  383. self.log.info('Removing volume %s: %s' % (name, volume.vid))
  384. try:
  385. ret = self.get_pool(volume).remove(volume)
  386. if asyncio.iscoroutine(ret):
  387. futures.append(ret)
  388. except (IOError, OSError) as e:
  389. self.vm.log.exception("Failed to remove volume %s", name, e)
  390. if futures:
  391. try:
  392. yield from asyncio.wait(futures)
  393. except (IOError, OSError) as e:
  394. self.vm.log.exception("Failed to remove some volume", e)
  395. @asyncio.coroutine
  396. def start(self):
  397. ''' Execute the start method on each pool '''
  398. futures = []
  399. for volume in self.vm.volumes.values():
  400. pool = self.get_pool(volume)
  401. ret = pool.start(volume)
  402. if asyncio.iscoroutine(ret):
  403. futures.append(ret)
  404. if futures:
  405. yield from asyncio.wait(futures)
  406. @asyncio.coroutine
  407. def stop(self):
  408. ''' Execute the start method on each pool '''
  409. futures = []
  410. for volume in self.vm.volumes.values():
  411. ret = self.get_pool(volume).stop(volume)
  412. if asyncio.iscoroutine(ret):
  413. futures.append(ret)
  414. if futures:
  415. yield from asyncio.wait(futures)
  416. def get_pool(self, volume):
  417. ''' Helper function '''
  418. assert isinstance(volume, (Volume, str)), \
  419. "You need to pass a Volume or pool name as str"
  420. if isinstance(volume, Volume):
  421. return self.pools[volume.name]
  422. return self.vm.app.pools[volume]
  423. @asyncio.coroutine
  424. def commit(self):
  425. ''' Makes changes to an 'origin' volume persistent '''
  426. futures = []
  427. for volume in self.vm.volumes.values():
  428. if volume.save_on_stop:
  429. ret = self.get_pool(volume).commit(volume)
  430. if asyncio.iscoroutine(ret):
  431. futures.append(ret)
  432. if futures:
  433. yield asyncio.wait(futures)
  434. def unused_frontend(self):
  435. ''' Find an unused device name '''
  436. unused_frontends = self.AVAILABLE_FRONTENDS.difference(
  437. self.used_frontends)
  438. return sorted(unused_frontends)[0]
  439. @property
  440. def used_frontends(self):
  441. ''' Used device names '''
  442. xml = self.vm.libvirt_domain.XMLDesc()
  443. parsed_xml = lxml.etree.fromstring(xml)
  444. return set([target.get('dev', None)
  445. for target in parsed_xml.xpath(
  446. "//domain/devices/disk/target")])
  447. def export(self, volume):
  448. ''' Helper function to export volume (pool.export(volume))'''
  449. assert isinstance(volume, (Volume, str)), \
  450. "You need to pass a Volume or pool name as str"
  451. if isinstance(volume, Volume):
  452. return self.pools[volume.name].export(volume)
  453. return self.pools[volume].export(self.vm.volumes[volume])
  454. class Pool(object):
  455. ''' A Pool is used to manage different kind of volumes (File
  456. based/LVM/Btrfs/...).
  457. 3rd Parties providing own storage implementations will need to extend
  458. this class.
  459. ''' # pylint: disable=unused-argument
  460. private_img_size = qubes.config.defaults['private_img_size']
  461. root_img_size = qubes.config.defaults['root_img_size']
  462. def __init__(self, name, revisions_to_keep=1, **kwargs):
  463. super(Pool, self).__init__(**kwargs)
  464. self.name = name
  465. self.revisions_to_keep = revisions_to_keep
  466. kwargs['name'] = self.name
  467. def __eq__(self, other):
  468. return self.name == other.name
  469. def __neq__(self, other):
  470. return not self.__eq__(other)
  471. def __str__(self):
  472. return self.name
  473. def __hash__(self):
  474. return hash(self.name)
  475. def __xml__(self):
  476. config = _sanitize_config(self.config)
  477. return lxml.etree.Element('pool', **config)
  478. def create(self, volume):
  479. ''' Create the given volume on disk or copy from provided
  480. `source_volume`.
  481. This can be implemented as a coroutine.
  482. '''
  483. raise self._not_implemented("create")
  484. def commit(self, volume): # pylint: disable=no-self-use
  485. ''' Write the snapshot to disk
  486. This can be implemented as a coroutine.'''
  487. msg = "Got volume_type {!s} when expected 'snap'"
  488. msg = msg.format(volume.volume_type)
  489. assert volume.volume_type == 'snap', msg
  490. @property
  491. def config(self):
  492. ''' Returns the pool config to be written to qubes.xml '''
  493. raise self._not_implemented("config")
  494. def clone(self, source, target):
  495. ''' Clone volume.
  496. This can be implemented as a coroutine. '''
  497. raise self._not_implemented("clone")
  498. def destroy(self):
  499. ''' Called when removing the pool. Use this for implementation specific
  500. clean up.
  501. '''
  502. raise self._not_implemented("destroy")
  503. def export(self, volume):
  504. ''' Returns an object that can be `open()`. '''
  505. raise self._not_implemented("export")
  506. def import_volume(self, dst_pool, dst_volume, src_pool, src_volume):
  507. ''' Imports data to a volume in this pool '''
  508. raise self._not_implemented("import_volume")
  509. def init_volume(self, vm, volume_config):
  510. ''' Initialize a :py:class:`qubes.storage.Volume` from `volume_config`.
  511. '''
  512. raise self._not_implemented("init_volume")
  513. def is_dirty(self, volume):
  514. ''' Return `True` if volume was not properly shutdown and commited '''
  515. raise self._not_implemented("is_dirty")
  516. def is_outdated(self, volume):
  517. ''' Returns `True` if the currently used `volume.source` of a snapshot
  518. volume is outdated.
  519. '''
  520. raise self._not_implemented("is_outdated")
  521. def recover(self, volume):
  522. ''' Try to recover a :py:class:`Volume` or :py:class:`SnapVolume` '''
  523. raise self._not_implemented("recover")
  524. def remove(self, volume):
  525. ''' Remove volume.
  526. This can be implemented as a coroutine.'''
  527. raise self._not_implemented("remove")
  528. def rename(self, volume, old_name, new_name):
  529. ''' Called when the domain changes its name '''
  530. raise self._not_implemented("rename")
  531. def reset(self, volume):
  532. ''' Drop and recreate volume without copying it's content from source.
  533. '''
  534. raise self._not_implemented("reset")
  535. def resize(self, volume, size):
  536. ''' Expands volume, throws
  537. :py:class:`qubes.storage.StoragePoolException` if
  538. given size is less than current_size
  539. This can be implemented as a coroutine.
  540. '''
  541. raise self._not_implemented("resize")
  542. def revert(self, volume, revision=None):
  543. ''' Revert volume to previous revision '''
  544. raise self._not_implemented("revert")
  545. def setup(self):
  546. ''' Called when adding a pool to the system. Use this for implementation
  547. specific set up.
  548. '''
  549. raise self._not_implemented("setup")
  550. def start(self, volume): # pylint: disable=no-self-use
  551. ''' Do what ever is needed on start
  552. This can be implemented as a coroutine.'''
  553. raise self._not_implemented("start")
  554. def stop(self, volume): # pylint: disable=no-self-use
  555. ''' Do what ever is needed on stop
  556. This can be implemented as a coroutine.'''
  557. def verify(self, volume):
  558. ''' Verifies the volume.
  559. This can be implemented as a coroutine.'''
  560. raise self._not_implemented("verify")
  561. @property
  562. def volumes(self):
  563. ''' Return a list of volumes managed by this pool '''
  564. raise self._not_implemented("volumes")
  565. def _not_implemented(self, method_name):
  566. ''' Helper for emitting helpful `NotImplementedError` exceptions '''
  567. msg = "Pool driver {!s} has {!s}() not implemented"
  568. msg = msg.format(str(self.__class__.__name__), method_name)
  569. return NotImplementedError(msg)
  570. def _sanitize_config(config):
  571. ''' Helper function to convert types to appropriate strings
  572. ''' # FIXME: find another solution for serializing basic types
  573. result = {}
  574. for key, value in config.items():
  575. if isinstance(value, bool):
  576. if value:
  577. result[key] = 'True'
  578. else:
  579. result[key] = str(value)
  580. return result
  581. def pool_drivers():
  582. """ Return a list of EntryPoints names """
  583. return [ep.name
  584. for ep in pkg_resources.iter_entry_points(STORAGE_ENTRY_POINT)]
  585. def driver_parameters(name):
  586. ''' Get __init__ parameters from a driver with out `self` & `name`. '''
  587. init_function = qubes.utils.get_entry_point_one(
  588. qubes.storage.STORAGE_ENTRY_POINT, name).__init__
  589. params = init_function.func_code.co_varnames
  590. ignored_params = ['self', 'name']
  591. return [p for p in params if p not in ignored_params]
  592. def isodate(seconds=time.time()):
  593. ''' Helper method which returns an iso date '''
  594. return datetime.utcfromtimestamp(seconds).isoformat("T")
  595. class VmCreationManager(object):
  596. ''' A `ContextManager` which cleans up if volume creation fails.
  597. ''' # pylint: disable=too-few-public-methods
  598. def __init__(self, vm):
  599. self.vm = vm
  600. def __enter__(self):
  601. pass
  602. def __exit__(self, type, value, tb): # pylint: disable=redefined-builtin
  603. if type is not None and value is not None and tb is not None:
  604. for volume in self.vm.volumes.values():
  605. try:
  606. pool = self.vm.storage.get_pool(volume)
  607. pool.remove(volume)
  608. except Exception: # pylint: disable=broad-except
  609. pass
  610. os.rmdir(self.vm.dir_path)