__init__.py 22 KB

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