__init__.py 34 KB

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