storage.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. '''Storage subsystem.'''
  21. class Volume(object):
  22. '''Storage volume.'''
  23. def __init__(self, app, pool=None, vid=None, vm=None, vm_name=None):
  24. '''Construct a Volume object.
  25. Volume may be identified using pool+vid, or vm+vm_name. Either of
  26. those argument pairs must be given.
  27. :param Qubes app: application instance
  28. :param str pool: pool name
  29. :param str vid: volume id (within pool)
  30. :param str vm: owner VM name
  31. :param str vm_name: name within owning VM (like 'private', 'root' etc)
  32. '''
  33. self.app = app
  34. if pool is None and vm is None:
  35. raise ValueError('Either pool or vm must be given')
  36. if pool is not None and vid is None:
  37. raise ValueError('If pool is given, vid must be too.')
  38. if vm is not None and vm_name is None:
  39. raise ValueError('If vm is given, vm_name must be too.')
  40. self._pool = pool
  41. self._vid = vid
  42. self._vm = vm
  43. self._vm_name = vm_name
  44. self._info = None
  45. def _qubesd_call(self, func_name, payload=None, payload_stream=None):
  46. '''Make a call to qubesd regarding this volume
  47. :param str func_name: API function name, like `Info` or `Resize`
  48. :param bytes payload: Payload to send.
  49. :param file payload_stream: Stream to pipe payload from. Only one of
  50. `payload` and `payload_stream` can be used.
  51. '''
  52. if self._vm is not None:
  53. method = 'admin.vm.volume.' + func_name
  54. dest = self._vm
  55. arg = self._vm_name
  56. else:
  57. if payload_stream:
  58. raise NotImplementedError(
  59. 'payload_stream not implemented for '
  60. 'admin.pool.volume.* calls')
  61. method = 'admin.pool.volume.' + func_name
  62. dest = 'dom0'
  63. arg = self._pool
  64. if payload is not None:
  65. payload = self._vid.encode('ascii') + b' ' + payload
  66. else:
  67. payload = self._vid.encode('ascii')
  68. return self.app.qubesd_call(dest, method, arg, payload=payload,
  69. payload_stream=payload_stream)
  70. def _fetch_info(self, force=True):
  71. '''Fetch volume properties
  72. Populate self._info dict
  73. :param bool force: refresh self._info, even if already populated.
  74. '''
  75. if not force and self._info is not None:
  76. return
  77. info = self._qubesd_call('Info')
  78. info = info.decode('ascii')
  79. self._info = dict([line.split('=', 1) for line in info.splitlines()])
  80. def __eq__(self, other):
  81. if isinstance(other, Volume):
  82. return self.pool == other.pool and self.vid == other.vid
  83. return NotImplemented
  84. @property
  85. def name(self):
  86. '''per-VM volume name, if available'''
  87. return self._vm_name
  88. @property
  89. def pool(self):
  90. '''Storage volume pool name.'''
  91. if self._pool is not None:
  92. return self._pool
  93. self._fetch_info()
  94. return str(self._info['pool'])
  95. @property
  96. def vid(self):
  97. '''Storage volume id, unique within given pool.'''
  98. if self._vid is not None:
  99. return self._vid
  100. self._fetch_info()
  101. return str(self._info['vid'])
  102. @property
  103. def size(self):
  104. '''Size of volume, in bytes.'''
  105. self._fetch_info(True)
  106. return int(self._info['size'])
  107. @property
  108. def usage(self):
  109. '''Used volume space, in bytes.'''
  110. self._fetch_info(True)
  111. return int(self._info['usage'])
  112. @property
  113. def rw(self):
  114. '''True if volume is read-write.'''
  115. self._fetch_info()
  116. return self._info['rw'] == 'True'
  117. @property
  118. def snap_on_start(self):
  119. '''Create a snapshot from source on VM start.'''
  120. self._fetch_info()
  121. return self._info['snap_on_start'] == 'True'
  122. @property
  123. def save_on_stop(self):
  124. '''Commit changes to original volume on VM stop.'''
  125. self._fetch_info()
  126. return self._info['save_on_stop'] == 'True'
  127. @property
  128. def source(self):
  129. '''Volume ID of source volume (for :py:attr:`snap_on_start`).
  130. If None, this volume itself will be used.
  131. '''
  132. self._fetch_info()
  133. if self._info['source']:
  134. return self._info['source']
  135. return None
  136. @property
  137. def internal(self):
  138. '''If `True` volume is hidden when qvm-block is used'''
  139. self._fetch_info()
  140. return self._info['internal'] == 'True'
  141. @property
  142. def revisions_to_keep(self):
  143. '''Number of revisions to keep around'''
  144. self._fetch_info()
  145. return int(self._info['revisions_to_keep'])
  146. def resize(self, size):
  147. '''Resize volume.
  148. Currently only extending is supported.
  149. :param int size: new size in bytes.
  150. '''
  151. self._qubesd_call('Resize', str(size).encode('ascii'))
  152. @property
  153. def revisions(self):
  154. ''' Returns iterable containing revision identifiers'''
  155. revisions = self._qubesd_call('ListSnapshots')
  156. return revisions.decode('ascii').splitlines()
  157. def revert(self, revision):
  158. ''' Revert volume to previous revision
  159. :param str revision: Revision identifier to revert to
  160. '''
  161. if not isinstance(revision, str):
  162. raise TypeError('revision must be a str')
  163. self._qubesd_call('Revert', revision.encode('ascii'))
  164. def import_data(self, stream):
  165. ''' Import volume data from a given file-like object.
  166. This function override existing volume content
  167. :param stream: file-like object, must support fileno()
  168. '''
  169. self._qubesd_call('Import', payload_stream=stream)
  170. def clone(self, source):
  171. ''' Clone data from sane volume of another VM.
  172. This function override existing volume content.
  173. This operation is implemented for VM volumes - those in vm.volumes
  174. collection (not pool.volumes).
  175. :param source: source volume object
  176. '''
  177. # pylint: disable=protected-access
  178. if source._vm_name is None or self._vm_name is None:
  179. raise NotImplementedError(
  180. 'Operation implemented only for VM volumes')
  181. if source._vm_name != self._vm_name:
  182. raise ValueError('Source and target volume must have the same type')
  183. # this call is to *source* volume, because we extract data from there
  184. source._qubesd_call('Clone', payload=str(self._vm).encode())
  185. class Pool(object):
  186. ''' A Pool is used to manage different kind of volumes (File
  187. based/LVM/Btrfs/...).
  188. '''
  189. def __init__(self, app, name=None):
  190. ''' Initialize storage pool wrapper
  191. :param app: Qubes() object
  192. :param name: name of the pool
  193. '''
  194. self.app = app
  195. self.name = name
  196. self._config = None
  197. def __str__(self):
  198. return self.name
  199. def __eq__(self, other):
  200. if isinstance(other, Pool):
  201. return self.name == other.name
  202. elif isinstance(other, str):
  203. return self.name == other
  204. return NotImplemented
  205. def __lt__(self, other):
  206. if isinstance(other, Pool):
  207. return self.name < other.name
  208. return NotImplemented
  209. @property
  210. def config(self):
  211. ''' Storage pool config '''
  212. if self._config is None:
  213. pool_info_data = self.app.qubesd_call(
  214. 'dom0', 'admin.pool.Info', self.name, None)
  215. pool_info_data = pool_info_data.decode('utf-8')
  216. assert pool_info_data.endswith('\n')
  217. pool_info_data = pool_info_data[:-1]
  218. self._config = dict(
  219. l.split('=', 1) for l in pool_info_data.splitlines())
  220. return self._config
  221. @property
  222. def driver(self):
  223. ''' Storage pool driver '''
  224. return self.config['driver']
  225. @property
  226. def volumes(self):
  227. ''' Volumes managed by this pool '''
  228. volumes_data = self.app.qubesd_call(
  229. 'dom0', 'admin.pool.volume.List', self.name, None)
  230. assert volumes_data.endswith(b'\n')
  231. volumes_data = volumes_data[:-1].decode('ascii')
  232. for vid in volumes_data.splitlines():
  233. yield Volume(self.app, self.name, vid)