__init__.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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 library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library 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 GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. """ Qubes storage system"""
  23. from __future__ import absolute_import
  24. import inspect
  25. import os
  26. import os.path
  27. import string # pylint: disable=deprecated-module
  28. import subprocess
  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:
  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:
  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. #: disk space used by this volume, can be smaller than :py:attr:`size`
  68. #: for sparse volumes
  69. usage = 0
  70. def __init__(self, name, pool, vid,
  71. revisions_to_keep=0, rw=False, save_on_stop=False, size=0,
  72. snap_on_start=False, source=None, **kwargs):
  73. ''' Initialize a volume.
  74. :param str name: The name of the volume inside owning domain
  75. :param Pool pool: The pool object
  76. :param str vid: Volume identifier needs to be unique in pool
  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
  80. start, instead of using volume own data
  81. :param bool save_on_stop: Write changes to the volume in
  82. vm.stop(), otherwise - discard
  83. :param Volume source: other volume in same pool to make snapshot
  84. from, required if *snap_on_start*=`True`
  85. :param str/int size: Size of the volume
  86. '''
  87. super(Volume, self).__init__(**kwargs)
  88. assert isinstance(pool, Pool)
  89. assert source is None or (isinstance(source, Volume)
  90. and source.pool == pool)
  91. if snap_on_start and source is None:
  92. msg = "snap_on_start specified on {!r} but no volume source set"
  93. msg = msg.format(name)
  94. raise StoragePoolException(msg)
  95. elif not snap_on_start and source is not None:
  96. msg = "source specified on {!r} but no snap_on_start set"
  97. msg = msg.format(name)
  98. raise StoragePoolException(msg)
  99. #: Name of the volume in a domain it's attached to (like `root` or
  100. #: `private`).
  101. self.name = str(name)
  102. #: :py:class:`Pool` instance owning this volume
  103. self.pool = pool
  104. #: How many revisions of the volume to keep. Each revision is created
  105. # at :py:meth:`stop`, if :py:attr:`save_on_stop` is True
  106. self.revisions_to_keep = int(revisions_to_keep)
  107. #: Should this volume be writable by domain.
  108. self.rw = rw
  109. #: Should volume state be saved or discarded at :py:meth:`stop`
  110. self.save_on_stop = save_on_stop
  111. self._size = int(size)
  112. #: Should the volume state be initialized with a snapshot of
  113. #: same-named volume of domain's template.
  114. self.snap_on_start = snap_on_start
  115. #: source volume for :py:attr:`snap_on_start` volumes
  116. self.source = source
  117. #: Volume unique (inside given pool) identifier
  118. self.vid = vid
  119. def __eq__(self, other):
  120. if isinstance(other, Volume):
  121. return other.pool == self.pool and other.vid == self.vid
  122. return NotImplemented
  123. def __hash__(self):
  124. return hash('%s:%s' % (self.pool, self.vid))
  125. def __neq__(self, other):
  126. return not self.__eq__(other)
  127. def __repr__(self):
  128. return '{!r}'.format(str(self.pool) + ':' + self.vid)
  129. def __str__(self):
  130. return str(self.vid)
  131. def __xml__(self):
  132. config = _sanitize_config(self.config)
  133. return lxml.etree.Element('volume', **config)
  134. def create(self):
  135. ''' Create the given volume on disk.
  136. This method is called only once in the volume lifetime. Before
  137. calling this method, no data on disk should be touched (in
  138. context of this volume).
  139. This can be implemented as a coroutine.
  140. '''
  141. raise self._not_implemented("create")
  142. def remove(self):
  143. ''' Remove volume.
  144. This can be implemented as a coroutine.'''
  145. raise self._not_implemented("remove")
  146. def export(self):
  147. ''' Returns a path to read the volume data from.
  148. Reading from this path when domain owning this volume is
  149. running (i.e. when :py:meth:`is_dirty` is True) should return the
  150. data from before domain startup.
  151. Reading from the path returned by this method should return the
  152. volume data. If extracting volume data require something more
  153. than just reading from file (for example connecting to some other
  154. domain, or decompressing the data), the returned path may be a pipe.
  155. '''
  156. raise self._not_implemented("export")
  157. def import_data(self):
  158. ''' Returns a path to overwrite volume data.
  159. This method is called after volume was already :py:meth:`create`-ed.
  160. Writing to this path should overwrite volume data. If importing
  161. volume data require something more than just writing to a file (
  162. for example connecting to some other domain, or converting data
  163. on the fly), the returned path may be a pipe.
  164. This can be implemented as a coroutine.
  165. '''
  166. raise self._not_implemented("import")
  167. def import_data_end(self, success):
  168. ''' End the data import operation. This may be used by pool
  169. implementation to commit changes, cleanup temporary files etc.
  170. This method is called regardless the operation was successful or not.
  171. This can be implemented as a coroutine.
  172. :param success: True if data import was successful, otherwise False
  173. '''
  174. # by default do nothing
  175. pass
  176. def import_volume(self, src_volume):
  177. ''' Imports data from a different volume (possibly in a different
  178. pool.
  179. The volume needs to be create()d first.
  180. This can be implemented as a coroutine. '''
  181. # pylint: disable=unused-argument
  182. raise self._not_implemented("import_volume")
  183. def is_dirty(self):
  184. ''' Return `True` if volume was not properly shutdown and committed.
  185. This include the situation when domain owning the volume is still
  186. running.
  187. '''
  188. raise self._not_implemented("is_dirty")
  189. def is_outdated(self):
  190. ''' Returns `True` if this snapshot of a source volume (for
  191. `snap_on_start`=True) is outdated.
  192. '''
  193. raise self._not_implemented("is_outdated")
  194. def resize(self, size):
  195. ''' Expands volume, throws
  196. :py:class:`qubes.storage.StoragePoolException` if
  197. given size is less than current_size
  198. This can be implemented as a coroutine.
  199. :param int size: new size in bytes
  200. '''
  201. # pylint: disable=unused-argument
  202. raise self._not_implemented("resize")
  203. def revert(self, revision=None):
  204. ''' Revert volume to previous revision
  205. This can be implemented as a coroutine.
  206. :param revision: revision to revert volume to, see :py:attr:`revisions`
  207. '''
  208. # pylint: disable=unused-argument
  209. raise self._not_implemented("revert")
  210. def start(self):
  211. ''' Do what ever is needed on start.
  212. This include making a snapshot of template's volume if
  213. :py:attr:`snap_on_start` is set.
  214. This can be implemented as a coroutine.'''
  215. raise self._not_implemented("start")
  216. def stop(self):
  217. ''' Do what ever is needed on stop.
  218. This include committing data if :py:attr:`save_on_stop` is set.
  219. This can be implemented as a coroutine.'''
  220. raise self._not_implemented("stop")
  221. def verify(self):
  222. ''' Verifies the volume.
  223. This function is supposed to either return :py:obj:`True`, or raise
  224. an exception.
  225. This can be implemented as a coroutine.'''
  226. raise self._not_implemented("verify")
  227. def block_device(self):
  228. ''' Return :py:class:`BlockDevice` for serialization in
  229. the libvirt XML template as <disk>.
  230. '''
  231. return BlockDevice(self.path, self.name, self.script,
  232. self.rw, self.domain, self.devtype)
  233. @property
  234. def revisions(self):
  235. ''' Returns a dict containing revision identifiers and time of their
  236. creation '''
  237. msg = "{!s} has revisions not implemented".format(self.__class__)
  238. raise NotImplementedError(msg)
  239. @property
  240. def size(self):
  241. ''' Volume size in bytes '''
  242. return self._size
  243. @size.setter
  244. def size(self, size):
  245. # pylint: disable=attribute-defined-outside-init
  246. self._size = int(size)
  247. @property
  248. def config(self):
  249. ''' return config data for serialization to qubes.xml '''
  250. result = {
  251. 'name': self.name,
  252. 'pool': str(self.pool),
  253. 'vid': self.vid,
  254. 'revisions_to_keep': self.revisions_to_keep,
  255. 'rw': self.rw,
  256. 'save_on_stop': self.save_on_stop,
  257. 'snap_on_start': self.snap_on_start,
  258. }
  259. if self.size:
  260. result['size'] = self.size
  261. if self.source:
  262. result['source'] = str(self.source)
  263. return result
  264. def _not_implemented(self, method_name):
  265. ''' Helper for emitting helpful `NotImplementedError` exceptions '''
  266. msg = "Volume {!s} has {!s}() not implemented"
  267. msg = msg.format(str(self.__class__.__name__), method_name)
  268. return NotImplementedError(msg)
  269. class Storage:
  270. ''' Class for handling VM virtual disks.
  271. This is base class for all other implementations, mostly with Xen on Linux
  272. in mind.
  273. '''
  274. AVAILABLE_FRONTENDS = {'xvd' + c for c in string.ascii_lowercase}
  275. def __init__(self, vm):
  276. #: Domain for which we manage storage
  277. self.vm = vm
  278. self.log = self.vm.log
  279. #: Additional drive (currently used only by HVM)
  280. self.drive = None
  281. if hasattr(vm, 'volume_config'):
  282. for name, conf in self.vm.volume_config.items():
  283. self.init_volume(name, conf)
  284. def _update_volume_config_source(self, name, volume_config):
  285. '''Retrieve 'source' volume from VM's template'''
  286. template = getattr(self.vm, 'template', None)
  287. # recursively lookup source volume - templates may be
  288. # chained (TemplateVM -> AppVM -> DispVM, where the
  289. # actual source should be used from TemplateVM)
  290. while template:
  291. source = template.volumes[name]
  292. volume_config['source'] = source
  293. volume_config['pool'] = source.pool
  294. volume_config['size'] = source.size
  295. if source.source is not None:
  296. template = getattr(template, 'template', None)
  297. else:
  298. break
  299. def init_volume(self, name, volume_config):
  300. ''' Initialize Volume instance attached to this domain '''
  301. if 'name' not in volume_config:
  302. volume_config['name'] = name
  303. if 'source' in volume_config:
  304. # we have no control over VM load order,
  305. # so initialize storage recursively if needed
  306. template = getattr(self.vm, 'template', None)
  307. if template and template.storage is None:
  308. template.storage = Storage(template)
  309. if volume_config['source'] is None:
  310. self._update_volume_config_source(name, volume_config)
  311. else:
  312. # if source is already specified, pool needs to be too
  313. pool = self.vm.app.get_pool(volume_config['pool'])
  314. volume_config['source'] = pool.volumes[volume_config['source']]
  315. # if pool still unknown, load default
  316. if 'pool' not in volume_config:
  317. volume_config['pool'] = \
  318. getattr(self.vm.app, 'default_pool_' + name)
  319. pool = self.vm.app.get_pool(volume_config['pool'])
  320. if 'internal' in volume_config:
  321. # migrate old config
  322. del volume_config['internal']
  323. volume = pool.init_volume(self.vm, volume_config)
  324. self.vm.volumes[name] = volume
  325. return volume
  326. def attach(self, volume, rw=False):
  327. ''' Attach a volume to the domain '''
  328. assert self.vm.is_running()
  329. if self._is_already_attached(volume):
  330. self.vm.log.info("{!r} already attached".format(volume))
  331. return
  332. try:
  333. frontend = self.unused_frontend()
  334. except IndexError:
  335. raise StoragePoolException("No unused frontend found")
  336. disk = lxml.etree.Element("disk")
  337. disk.set('type', 'block')
  338. disk.set('device', 'disk')
  339. lxml.etree.SubElement(disk, 'driver').set('name', 'phy')
  340. lxml.etree.SubElement(disk, 'source').set('dev', '/dev/%s' % volume.vid)
  341. lxml.etree.SubElement(disk, 'target').set('dev', frontend)
  342. if not rw:
  343. lxml.etree.SubElement(disk, 'readonly')
  344. if volume.domain is not None:
  345. lxml.etree.SubElement(disk, 'backenddomain').set(
  346. 'name', volume.domain.name)
  347. xml_string = lxml.etree.tostring(disk, encoding='utf-8')
  348. self.vm.libvirt_domain.attachDevice(xml_string)
  349. # trigger watches to update device status
  350. # FIXME: this should be removed once libvirt will report such
  351. # events itself
  352. # self.vm.untrusted_qdb.write('/qubes-block-devices', '')
  353. # ← do we need this?
  354. def _is_already_attached(self, volume):
  355. ''' Checks if the given volume is already attached '''
  356. parsed_xml = lxml.etree.fromstring(self.vm.libvirt_domain.XMLDesc())
  357. disk_sources = parsed_xml.xpath("//domain/devices/disk/source")
  358. for source in disk_sources:
  359. if source.get('dev') == '/dev/%s' % volume.vid:
  360. return True
  361. return False
  362. def detach(self, volume):
  363. ''' Detach a volume from domain '''
  364. parsed_xml = lxml.etree.fromstring(self.vm.libvirt_domain.XMLDesc())
  365. disks = parsed_xml.xpath("//domain/devices/disk")
  366. for disk in disks:
  367. source = disk.xpath('source')[0]
  368. if source.get('dev') == '/dev/%s' % volume.vid:
  369. disk_xml = lxml.etree.tostring(disk, encoding='utf-8')
  370. self.vm.libvirt_domain.detachDevice(disk_xml)
  371. return
  372. raise StoragePoolException('Volume {!r} is not attached'.format(volume))
  373. @property
  374. def kernels_dir(self):
  375. '''Directory where kernel resides.
  376. If :py:attr:`self.vm.kernel` is :py:obj:`None`, the this points inside
  377. :py:attr:`self.vm.dir_path`
  378. '''
  379. assert 'kernel' in self.vm.volumes, "VM has no kernel volume"
  380. return self.vm.volumes['kernel'].kernels_dir
  381. def get_disk_utilization(self):
  382. ''' Returns summed up disk utilization for all domain volumes '''
  383. result = 0
  384. for volume in self.vm.volumes.values():
  385. result += volume.usage
  386. return result
  387. @asyncio.coroutine
  388. def resize(self, volume, size):
  389. ''' Resizes volume a read-writable volume '''
  390. if isinstance(volume, str):
  391. volume = self.vm.volumes[volume]
  392. ret = volume.resize(size)
  393. if asyncio.iscoroutine(ret):
  394. yield from ret
  395. if self.vm.is_running():
  396. try:
  397. yield from self.vm.run_service_for_stdio('qubes.ResizeDisk',
  398. input=volume.name.encode(),
  399. user='root')
  400. except subprocess.CalledProcessError as e:
  401. service_error = e.stderr.decode('ascii', errors='ignore')
  402. service_error = service_error.replace('%', '')
  403. raise StoragePoolException(
  404. 'Online resize of volume {} failed (you need to resize '
  405. 'filesystem manually): {}'.format(volume, service_error))
  406. @asyncio.coroutine
  407. def create(self):
  408. ''' Creates volumes on disk '''
  409. old_umask = os.umask(0o002)
  410. coros = []
  411. for volume in self.vm.volumes.values():
  412. # launch the operation, if it's asynchronous, then append to wait
  413. # for them at the end
  414. ret = volume.create()
  415. if asyncio.iscoroutine(ret):
  416. coros.append(ret)
  417. yield from _wait_and_reraise(coros)
  418. os.umask(old_umask)
  419. @asyncio.coroutine
  420. def clone_volume(self, src_vm, name):
  421. ''' Clone single volume from the specified vm
  422. :param QubesVM src_vm: source VM
  423. :param str name: name of volume to clone ('root', 'private' etc)
  424. :return cloned volume object
  425. '''
  426. config = self.vm.volume_config[name]
  427. dst_pool = self.vm.app.get_pool(config['pool'])
  428. dst = dst_pool.init_volume(self.vm, config)
  429. src_volume = src_vm.volumes[name]
  430. msg = "Importing volume {!s} from vm {!s}"
  431. self.vm.log.info(msg.format(src_volume.name, src_vm.name))
  432. # First create the destination volume
  433. create_op_ret = dst.create()
  434. # clone/import functions may be either synchronous or asynchronous
  435. # in the later case, we need to wait for them to finish
  436. if asyncio.iscoroutine(create_op_ret):
  437. yield from create_op_ret
  438. # Then import data from source volume
  439. clone_op_ret = dst.import_volume(src_volume)
  440. # clone/import functions may be either synchronous or asynchronous
  441. # in the later case, we need to wait for them to finish
  442. if asyncio.iscoroutine(clone_op_ret):
  443. yield from clone_op_ret
  444. self.vm.volumes[name] = dst
  445. return self.vm.volumes[name]
  446. @asyncio.coroutine
  447. def clone(self, src_vm):
  448. ''' Clone volumes from the specified vm '''
  449. self.vm.volumes = {}
  450. with VmCreationManager(self.vm):
  451. yield from _wait_and_reraise([self.clone_volume(src_vm, vol_name)
  452. for vol_name in self.vm.volume_config.keys()])
  453. @property
  454. def outdated_volumes(self):
  455. ''' Returns a list of outdated volumes '''
  456. result = []
  457. if self.vm.is_halted():
  458. return result
  459. volumes = self.vm.volumes
  460. for volume in volumes.values():
  461. if volume.is_outdated():
  462. result += [volume]
  463. return result
  464. @asyncio.coroutine
  465. def verify(self):
  466. '''Verify that the storage is sane.
  467. On success, returns normally. On failure, raises exception.
  468. '''
  469. if not os.path.exists(self.vm.dir_path):
  470. raise qubes.exc.QubesVMError(
  471. self.vm,
  472. 'VM directory does not exist: {}'.format(self.vm.dir_path))
  473. futures = []
  474. for volume in self.vm.volumes.values():
  475. ret = volume.verify()
  476. if asyncio.iscoroutine(ret):
  477. futures.append(ret)
  478. yield from _wait_and_reraise(futures)
  479. self.vm.fire_event('domain-verify-files')
  480. return True
  481. @asyncio.coroutine
  482. def remove(self):
  483. ''' Remove all the volumes.
  484. Errors on removal are catched and logged.
  485. '''
  486. futures = []
  487. for name, volume in self.vm.volumes.items():
  488. self.log.info('Removing volume %s: %s' % (name, volume.vid))
  489. try:
  490. ret = volume.remove()
  491. if asyncio.iscoroutine(ret):
  492. futures.append(ret)
  493. except (IOError, OSError) as e:
  494. self.vm.log.exception("Failed to remove volume %s", name, e)
  495. try:
  496. yield from _wait_and_reraise(futures)
  497. except (IOError, OSError) as e:
  498. self.vm.log.exception("Failed to remove some volume", e)
  499. @asyncio.coroutine
  500. def start(self):
  501. ''' Execute the start method on each volume '''
  502. futures = []
  503. for volume in self.vm.volumes.values():
  504. ret = volume.start()
  505. if asyncio.iscoroutine(ret):
  506. futures.append(ret)
  507. yield from _wait_and_reraise(futures)
  508. @asyncio.coroutine
  509. def stop(self):
  510. ''' Execute the stop method on each volume '''
  511. futures = []
  512. for volume in self.vm.volumes.values():
  513. ret = volume.stop()
  514. if asyncio.iscoroutine(ret):
  515. futures.append(ret)
  516. yield from _wait_and_reraise(futures)
  517. def unused_frontend(self):
  518. ''' Find an unused device name '''
  519. unused_frontends = self.AVAILABLE_FRONTENDS.difference(
  520. self.used_frontends)
  521. return sorted(unused_frontends)[0]
  522. @property
  523. def used_frontends(self):
  524. ''' Used device names '''
  525. xml = self.vm.libvirt_domain.XMLDesc()
  526. parsed_xml = lxml.etree.fromstring(xml)
  527. return {target.get('dev', None)
  528. for target in parsed_xml.xpath(
  529. "//domain/devices/disk/target")}
  530. def export(self, volume):
  531. ''' Helper function to export volume (pool.export(volume))'''
  532. assert isinstance(volume, (Volume, str)), \
  533. "You need to pass a Volume or pool name as str"
  534. if isinstance(volume, Volume):
  535. return volume.export()
  536. return self.vm.volumes[volume].export()
  537. @asyncio.coroutine
  538. def import_data(self, volume):
  539. ''' Helper function to import volume data (pool.import_data(volume))'''
  540. assert isinstance(volume, (Volume, str)), \
  541. "You need to pass a Volume or pool name as str"
  542. if isinstance(volume, Volume):
  543. ret = volume.import_data()
  544. else:
  545. ret = self.vm.volumes[volume].import_data()
  546. if asyncio.iscoroutine(ret):
  547. ret = yield from ret
  548. return ret
  549. @asyncio.coroutine
  550. def import_data_end(self, volume, success):
  551. ''' Helper function to finish/cleanup data import
  552. (pool.import_data_end( volume))'''
  553. assert isinstance(volume, (Volume, str)), \
  554. "You need to pass a Volume or pool name as str"
  555. if isinstance(volume, Volume):
  556. ret = volume.import_data_end(success=success)
  557. else:
  558. ret = self.vm.volumes[volume].import_data_end(success=success)
  559. if asyncio.iscoroutine(ret):
  560. ret = yield from ret
  561. return ret
  562. class VolumesCollection:
  563. '''Convenient collection wrapper for pool.get_volume and
  564. pool.list_volumes
  565. '''
  566. def __init__(self, pool):
  567. self._pool = pool
  568. def __getitem__(self, item):
  569. ''' Get a single volume with given Volume ID.
  570. You can also a Volume instance to get the same Volume or KeyError if
  571. Volume no longer exists.
  572. :param item: a Volume ID (str) or a Volume instance
  573. '''
  574. if isinstance(item, Volume):
  575. if item.pool == self._pool:
  576. return self[item.vid]
  577. raise KeyError(item)
  578. try:
  579. return self._pool.get_volume(item)
  580. except NotImplementedError:
  581. for vol in self:
  582. if vol.vid == item:
  583. return vol
  584. # if list_volumes is not implemented too, it will raise
  585. # NotImplementedError again earlier
  586. raise KeyError(item)
  587. def __iter__(self):
  588. ''' Get iterator over pool's volumes '''
  589. return iter(self._pool.list_volumes())
  590. def __contains__(self, item):
  591. ''' Check if given volume (either Volume ID or Volume instance) is
  592. present in the pool
  593. '''
  594. try:
  595. return self[item] is not None
  596. except KeyError:
  597. return False
  598. def keys(self):
  599. ''' Return list of volume IDs '''
  600. return [vol.vid for vol in self]
  601. def values(self):
  602. ''' Return list of Volumes'''
  603. return [vol for vol in self]
  604. class Pool:
  605. ''' A Pool is used to manage different kind of volumes (File
  606. based/LVM/Btrfs/...).
  607. 3rd Parties providing own storage implementations will need to extend
  608. this class.
  609. ''' # pylint: disable=unused-argument
  610. private_img_size = qubes.config.defaults['private_img_size']
  611. root_img_size = qubes.config.defaults['root_img_size']
  612. def __init__(self, name, revisions_to_keep=1, **kwargs):
  613. super(Pool, self).__init__(**kwargs)
  614. self._volumes_collection = VolumesCollection(self)
  615. self.name = name
  616. self.revisions_to_keep = revisions_to_keep
  617. kwargs['name'] = self.name
  618. def __eq__(self, other):
  619. if isinstance(other, Pool):
  620. return self.name == other.name
  621. if isinstance(other, str):
  622. return self.name == other
  623. return NotImplemented
  624. def __neq__(self, other):
  625. return not self.__eq__(other)
  626. def __str__(self):
  627. return self.name
  628. def __hash__(self):
  629. return hash(self.name)
  630. def __xml__(self):
  631. config = _sanitize_config(self.config)
  632. return lxml.etree.Element('pool', **config)
  633. @property
  634. def config(self):
  635. ''' Returns the pool config to be written to qubes.xml '''
  636. raise self._not_implemented("config")
  637. def destroy(self):
  638. ''' Called when removing the pool. Use this for implementation specific
  639. clean up.
  640. '''
  641. raise self._not_implemented("destroy")
  642. def init_volume(self, vm, volume_config):
  643. ''' Initialize a :py:class:`qubes.storage.Volume` from `volume_config`.
  644. '''
  645. raise self._not_implemented("init_volume")
  646. def setup(self):
  647. ''' Called when adding a pool to the system. Use this for implementation
  648. specific set up.
  649. '''
  650. raise self._not_implemented("setup")
  651. @property
  652. def volumes(self):
  653. ''' Return a collection of volumes managed by this pool '''
  654. return self._volumes_collection
  655. def list_volumes(self):
  656. ''' Return a list of volumes managed by this pool '''
  657. raise self._not_implemented("list_volumes")
  658. def get_volume(self, vid):
  659. ''' Return a volume with *vid* from this pool
  660. :raise KeyError: if no volume is found
  661. '''
  662. raise self._not_implemented("get_volume")
  663. def included_in(self, app):
  664. ''' Check if this pool is physically included in another one
  665. This works on best-effort basis, because one pool driver may not know
  666. all the other drivers.
  667. :param app: Qubes() object to lookup other pools in
  668. :returns pool or None
  669. '''
  670. pass
  671. @property
  672. def size(self):
  673. ''' Storage pool size in bytes, or None if unknown '''
  674. pass
  675. @property
  676. def usage(self):
  677. ''' Space used in the pool in bytes, or None if unknown '''
  678. pass
  679. def _not_implemented(self, method_name):
  680. ''' Helper for emitting helpful `NotImplementedError` exceptions '''
  681. msg = "Pool driver {!s} has {!s}() not implemented"
  682. msg = msg.format(str(self.__class__.__name__), method_name)
  683. return NotImplementedError(msg)
  684. @asyncio.coroutine
  685. def _wait_and_reraise(futures):
  686. if futures:
  687. done, _ = yield from asyncio.wait(futures)
  688. for task in done: # (re-)raise first exception in line
  689. task.result()
  690. def _sanitize_config(config):
  691. ''' Helper function to convert types to appropriate strings
  692. ''' # FIXME: find another solution for serializing basic types
  693. result = {}
  694. for key, value in config.items():
  695. if isinstance(value, bool):
  696. if value:
  697. result[key] = 'True'
  698. else:
  699. result[key] = str(value)
  700. return result
  701. def pool_drivers():
  702. """ Return a list of EntryPoints names """
  703. return [ep.name
  704. for ep in pkg_resources.iter_entry_points(STORAGE_ENTRY_POINT)]
  705. def driver_parameters(name):
  706. ''' Get __init__ parameters from a driver with out `self` & `name`. '''
  707. init_function = qubes.utils.get_entry_point_one(
  708. qubes.storage.STORAGE_ENTRY_POINT, name).__init__
  709. signature = inspect.signature(init_function)
  710. params = signature.parameters.keys()
  711. ignored_params = ['self', 'name', 'kwargs']
  712. return [p for p in params if p not in ignored_params]
  713. def isodate(seconds):
  714. ''' Helper method which returns an iso date '''
  715. return datetime.utcfromtimestamp(seconds).isoformat("T")
  716. def search_pool_containing_dir(pools, dir_path):
  717. ''' Helper function looking for a pool containing given directory.
  718. This is useful for implementing Pool.included_in method
  719. '''
  720. real_dir_path = os.path.realpath(dir_path)
  721. # prefer filesystem pools
  722. for pool in pools:
  723. if hasattr(pool, 'dir_path'):
  724. pool_real_dir_path = os.path.realpath(pool.dir_path)
  725. if os.path.commonpath([pool_real_dir_path, real_dir_path]) == \
  726. pool_real_dir_path:
  727. return pool
  728. # then look for lvm
  729. for pool in pools:
  730. if hasattr(pool, 'thin_pool') and hasattr(pool, 'volume_group'):
  731. if (pool.volume_group, pool.thin_pool) == \
  732. DirectoryThinPool.thin_pool(real_dir_path):
  733. return pool
  734. return None
  735. class VmCreationManager:
  736. ''' A `ContextManager` which cleans up if volume creation fails.
  737. ''' # pylint: disable=too-few-public-methods
  738. def __init__(self, vm):
  739. self.vm = vm
  740. def __enter__(self):
  741. pass
  742. def __exit__(self, type, value, tb): # pylint: disable=redefined-builtin
  743. if type is not None and value is not None and tb is not None:
  744. for volume in self.vm.volumes.values():
  745. try:
  746. volume.remove()
  747. except Exception: # pylint: disable=broad-except
  748. pass
  749. os.rmdir(self.vm.dir_path)
  750. # pylint: disable=too-few-public-methods
  751. class DirectoryThinPool:
  752. '''The thin pool containing the device of given filesystem'''
  753. _thin_pool = {}
  754. @classmethod
  755. def _init(cls, dir_path):
  756. '''Find out the thin pool containing given filesystem'''
  757. if dir_path not in cls._thin_pool:
  758. cls._thin_pool[dir_path] = None, None
  759. try:
  760. fs_stat = os.stat(dir_path)
  761. fs_major = (fs_stat.st_dev & 0xff00) >> 8
  762. fs_minor = fs_stat.st_dev & 0xff
  763. sudo = []
  764. if os.getuid():
  765. sudo = ['sudo']
  766. root_table = subprocess.check_output(sudo + ["dmsetup",
  767. "-j", str(fs_major), "-m", str(fs_minor),
  768. "table"], stderr=subprocess.DEVNULL)
  769. _start, _sectors, target_type, target_args = \
  770. root_table.decode().split(" ", 3)
  771. if target_type == "thin":
  772. thin_pool_devnum, _thin_pool_id = target_args.split(" ")
  773. with open("/sys/dev/block/{}/dm/name"
  774. .format(thin_pool_devnum), "r") as thin_pool_tpool_f:
  775. thin_pool_tpool = thin_pool_tpool_f.read().rstrip('\n')
  776. if thin_pool_tpool.endswith("-tpool"):
  777. volume_group, thin_pool, _tpool = \
  778. thin_pool_tpool.rsplit("-", 2)
  779. cls._thin_pool[dir_path] = volume_group, thin_pool
  780. except: # pylint: disable=bare-except
  781. pass
  782. @classmethod
  783. def thin_pool(cls, dir_path):
  784. '''Thin tuple (volume group, pool name) containing given filesystem'''
  785. cls._init(dir_path)
  786. return cls._thin_pool[dir_path]