__init__.py 23 KB

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