__init__.py 26 KB

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