__init__.py 33 KB

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