Coverage for drivers/linstorvhdutil.py : 23%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1#!/usr/bin/env python3
2#
3# Copyright (C) 2020 Vates SAS - ronan.abhamon@vates.fr
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program. If not, see <https://www.gnu.org/licenses/>.
17from linstorjournaler import LinstorJournaler
18from linstorvolumemanager import LinstorVolumeManager
19import base64
20import distutils.util
21import errno
22import json
23import socket
24import util
25import vhdutil
26import xs_errors
28MANAGER_PLUGIN = 'linstor-manager'
31def call_remote_method(session, host_ref, method, device_path, args):
32 try:
33 response = session.xenapi.host.call_plugin(
34 host_ref, MANAGER_PLUGIN, method, args
35 )
36 except Exception as e:
37 util.SMlog('call-plugin ({} with {}) exception: {}'.format(
38 method, args, e
39 ))
40 raise util.SMException(str(e))
42 util.SMlog('call-plugin ({} with {}) returned: {}'.format(
43 method, args, response
44 ))
46 return response
49class LinstorCallException(util.SMException):
50 def __init__(self, cmd_err):
51 self.cmd_err = cmd_err
53 def __str__(self):
54 return str(self.cmd_err)
57class ErofsLinstorCallException(LinstorCallException):
58 pass
61class NoPathLinstorCallException(LinstorCallException):
62 pass
65def linstorhostcall(local_method, remote_method):
66 def decorated(response_parser):
67 def wrapper(*args, **kwargs):
68 self = args[0]
69 vdi_uuid = args[1]
71 device_path = self._linstor.build_device_path(
72 self._linstor.get_volume_name(vdi_uuid)
73 )
75 # A. Try a call using directly the DRBD device to avoid
76 # remote request.
78 # Try to read locally if the device is not in use or if the device
79 # is up to date and not diskless.
80 (node_names, in_use_by) = \
81 self._linstor.find_up_to_date_diskful_nodes(vdi_uuid)
83 local_e = None
84 try:
85 if not in_use_by or socket.gethostname() in node_names:
86 return self._call_local_method(local_method, device_path, *args[2:], **kwargs)
87 except ErofsLinstorCallException as e:
88 local_e = e.cmd_err
89 except Exception as e:
90 local_e = e
92 util.SMlog(
93 'unable to execute `{}` locally, retry using a readable host... (cause: {})'.format(
94 remote_method, local_e if local_e else 'local diskless + in use or not up to date'
95 )
96 )
98 if in_use_by:
99 node_names = {in_use_by}
101 # B. Execute the plugin on master or slave.
102 remote_args = {
103 'devicePath': device_path,
104 'groupName': self._linstor.group_name
105 }
106 remote_args.update(**kwargs)
107 remote_args = {str(key): str(value) for key, value in remote_args.items()}
109 try:
110 def remote_call():
111 host_ref = self._get_readonly_host(vdi_uuid, device_path, node_names)
112 return call_remote_method(self._session, host_ref, remote_method, device_path, remote_args)
113 response = util.retry(remote_call, 5, 2)
114 except Exception as remote_e:
115 self._raise_openers_exception(device_path, local_e or remote_e)
117 return response_parser(self, vdi_uuid, response)
118 return wrapper
119 return decorated
122def linstormodifier():
123 def decorated(func):
124 def wrapper(*args, **kwargs):
125 self = args[0]
127 ret = func(*args, **kwargs)
128 self._linstor.invalidate_resource_cache()
129 return ret
130 return wrapper
131 return decorated
134class LinstorVhdUtil:
135 MAX_SIZE = 2 * 1024 * 1024 * 1024 * 1024 # Max VHD size.
137 def __init__(self, session, linstor):
138 self._session = session
139 self._linstor = linstor
141 # --------------------------------------------------------------------------
142 # Getters: read locally and try on another host in case of failure.
143 # --------------------------------------------------------------------------
145 def check(self, vdi_uuid, ignore_missing_footer=False, fast=False):
146 kwargs = {
147 'ignoreMissingFooter': ignore_missing_footer,
148 'fast': fast
149 }
150 return self._check(vdi_uuid, **kwargs) # pylint: disable = E1123
152 @linstorhostcall(vhdutil.check, 'check')
153 def _check(self, vdi_uuid, response):
154 return distutils.util.strtobool(response)
156 def get_vhd_info(self, vdi_uuid, include_parent=True):
157 kwargs = {
158 'includeParent': include_parent,
159 'resolveParent': False
160 }
161 # TODO: Replace pylint comment with this feature when possible:
162 # https://github.com/PyCQA/pylint/pull/2926
163 return self._get_vhd_info(vdi_uuid, self._extract_uuid, **kwargs) # pylint: disable = E1123
165 @linstorhostcall(vhdutil.getVHDInfo, 'getVHDInfo')
166 def _get_vhd_info(self, vdi_uuid, response):
167 obj = json.loads(response)
169 vhd_info = vhdutil.VHDInfo(vdi_uuid)
170 vhd_info.sizeVirt = obj['sizeVirt']
171 vhd_info.sizePhys = obj['sizePhys']
172 if 'parentPath' in obj:
173 vhd_info.parentPath = obj['parentPath']
174 vhd_info.parentUuid = obj['parentUuid']
175 vhd_info.hidden = obj['hidden']
176 vhd_info.path = obj['path']
178 return vhd_info
180 @linstorhostcall(vhdutil.hasParent, 'hasParent')
181 def has_parent(self, vdi_uuid, response):
182 return distutils.util.strtobool(response)
184 def get_parent(self, vdi_uuid):
185 return self._get_parent(vdi_uuid, self._extract_uuid)
187 @linstorhostcall(vhdutil.getParent, 'getParent')
188 def _get_parent(self, vdi_uuid, response):
189 return response
191 @linstorhostcall(vhdutil.getSizeVirt, 'getSizeVirt')
192 def get_size_virt(self, vdi_uuid, response):
193 return int(response)
195 @linstorhostcall(vhdutil.getSizePhys, 'getSizePhys')
196 def get_size_phys(self, vdi_uuid, response):
197 return int(response)
199 @linstorhostcall(vhdutil.getDepth, 'getDepth')
200 def get_depth(self, vdi_uuid, response):
201 return int(response)
203 @linstorhostcall(vhdutil.getKeyHash, 'getKeyHash')
204 def get_key_hash(self, vdi_uuid, response):
205 return response or None
207 @linstorhostcall(vhdutil.getBlockBitmap, 'getBlockBitmap')
208 def get_block_bitmap(self, vdi_uuid, response):
209 return base64.b64decode(response)
211 @linstorhostcall('_get_drbd_size', 'getDrbdSize')
212 def get_drbd_size(self, vdi_uuid, response):
213 return int(response)
215 def _get_drbd_size(self, path):
216 (ret, stdout, stderr) = util.doexec(['blockdev', '--getsize64', path])
217 if ret == 0:
218 return int(stdout.strip())
219 raise util.SMException('Failed to get DRBD size: {}'.format(stderr))
221 # --------------------------------------------------------------------------
222 # Setters: only used locally.
223 # --------------------------------------------------------------------------
225 @linstormodifier()
226 def create(self, path, size, static, msize=0):
227 return self._call_local_method_or_fail(vhdutil.create, path, size, static, msize)
229 @linstormodifier()
230 def set_size_virt(self, path, size, jfile):
231 return self._call_local_method_or_fail(vhdutil.setSizeVirt, path, size, jfile)
233 @linstormodifier()
234 def set_size_virt_fast(self, path, size):
235 return self._call_local_method_or_fail(vhdutil.setSizeVirtFast, path, size)
237 @linstormodifier()
238 def set_size_phys(self, path, size, debug=True):
239 return self._call_local_method_or_fail(vhdutil.setSizePhys, path, size, debug)
241 @linstormodifier()
242 def set_parent(self, path, parentPath, parentRaw=False):
243 return self._call_local_method_or_fail(vhdutil.setParent, path, parentPath, parentRaw)
245 @linstormodifier()
246 def set_hidden(self, path, hidden=True):
247 return self._call_local_method_or_fail(vhdutil.setHidden, path, hidden)
249 @linstormodifier()
250 def set_key(self, path, key_hash):
251 return self._call_local_method_or_fail(vhdutil.setKey, path, key_hash)
253 @linstormodifier()
254 def kill_data(self, path):
255 return self._call_local_method_or_fail(vhdutil.killData, path)
257 @linstormodifier()
258 def snapshot(self, path, parent, parentRaw, msize=0, checkEmpty=True):
259 return self._call_local_method_or_fail(vhdutil.snapshot, path, parent, parentRaw, msize, checkEmpty)
261 def inflate(self, journaler, vdi_uuid, vdi_path, new_size, old_size):
262 # Only inflate if the LINSTOR volume capacity is not enough.
263 new_size = LinstorVolumeManager.round_up_volume_size(new_size)
264 if new_size <= old_size:
265 return
267 util.SMlog(
268 'Inflate {} (size={}, previous={})'
269 .format(vdi_path, new_size, old_size)
270 )
272 journaler.create(
273 LinstorJournaler.INFLATE, vdi_uuid, old_size
274 )
275 self._linstor.resize_volume(vdi_uuid, new_size)
277 # TODO: Replace pylint comment with this feature when possible:
278 # https://github.com/PyCQA/pylint/pull/2926
279 result_size = self.get_drbd_size(vdi_uuid) # pylint: disable = E1120
280 if result_size < new_size:
281 util.SMlog(
282 'WARNING: Cannot inflate volume to {}B, result size: {}B'
283 .format(new_size, result_size)
284 )
286 self._zeroize(vdi_path, result_size - vhdutil.VHD_FOOTER_SIZE)
287 self.set_size_phys(vdi_path, result_size, False)
288 journaler.remove(LinstorJournaler.INFLATE, vdi_uuid)
290 def deflate(self, vdi_path, new_size, old_size, zeroize=False):
291 if zeroize:
292 assert old_size > vhdutil.VHD_FOOTER_SIZE
293 self._zeroize(vdi_path, old_size - vhdutil.VHD_FOOTER_SIZE)
295 new_size = LinstorVolumeManager.round_up_volume_size(new_size)
296 if new_size >= old_size:
297 return
299 util.SMlog(
300 'Deflate {} (new size={}, previous={})'
301 .format(vdi_path, new_size, old_size)
302 )
304 self.set_size_phys(vdi_path, new_size)
305 # TODO: Change the LINSTOR volume size using linstor.resize_volume.
307 # --------------------------------------------------------------------------
308 # Remote setters: write locally and try on another host in case of failure.
309 # --------------------------------------------------------------------------
311 @linstormodifier()
312 def force_parent(self, path, parentPath, parentRaw=False):
313 kwargs = {
314 'parentPath': str(parentPath),
315 'parentRaw': parentRaw
316 }
317 return self._call_method(vhdutil.setParent, 'setParent', path, use_parent=False, **kwargs)
319 @linstormodifier()
320 def force_coalesce(self, path):
321 return self._call_method(vhdutil.coalesce, 'coalesce', path, use_parent=True)
323 @linstormodifier()
324 def force_repair(self, path):
325 return self._call_method(vhdutil.repair, 'repair', path, use_parent=False)
327 @linstormodifier()
328 def force_deflate(self, path, newSize, oldSize, zeroize):
329 kwargs = {
330 'newSize': newSize,
331 'oldSize': oldSize,
332 'zeroize': zeroize
333 }
334 return self._call_method('_force_deflate', 'deflate', path, use_parent=False, **kwargs)
336 def _force_deflate(self, path, newSize, oldSize, zeroize):
337 self.deflate(path, newSize, oldSize, zeroize)
339 # --------------------------------------------------------------------------
340 # Static helpers.
341 # --------------------------------------------------------------------------
343 @classmethod
344 def compute_volume_size(cls, virtual_size, image_type):
345 if image_type == vhdutil.VDI_TYPE_VHD:
346 # All LINSTOR VDIs have the metadata area preallocated for
347 # the maximum possible virtual size (for fast online VDI.resize).
348 meta_overhead = vhdutil.calcOverheadEmpty(cls.MAX_SIZE)
349 bitmap_overhead = vhdutil.calcOverheadBitmap(virtual_size)
350 virtual_size += meta_overhead + bitmap_overhead
351 elif image_type != vhdutil.VDI_TYPE_RAW:
352 raise Exception('Invalid image type: {}'.format(image_type))
354 return LinstorVolumeManager.round_up_volume_size(virtual_size)
356 # --------------------------------------------------------------------------
357 # Helpers.
358 # --------------------------------------------------------------------------
360 def _extract_uuid(self, device_path):
361 # TODO: Remove new line in the vhdutil module. Not here.
362 return self._linstor.get_volume_uuid_from_device_path(
363 device_path.rstrip('\n')
364 )
366 def _get_readonly_host(self, vdi_uuid, device_path, node_names):
367 """
368 When vhd-util is called to fetch VDI info we must find a
369 diskful DRBD disk to read the data. It's the goal of this function.
370 Why? Because when a VHD is open in RO mode, the LVM layer is used
371 directly to bypass DRBD verifications (we can have only one process
372 that reads/writes to disk with DRBD devices).
373 """
375 if not node_names:
376 raise xs_errors.XenError(
377 'VDIUnavailable',
378 opterr='Unable to find diskful node: {} (path={})'
379 .format(vdi_uuid, device_path)
380 )
382 hosts = self._session.xenapi.host.get_all_records()
383 for host_ref, host_record in hosts.items():
384 if host_record['hostname'] in node_names:
385 return host_ref
387 raise xs_errors.XenError(
388 'VDIUnavailable',
389 opterr='Unable to find a valid host from VDI: {} (path={})'
390 .format(vdi_uuid, device_path)
391 )
393 # --------------------------------------------------------------------------
395 def _raise_openers_exception(self, device_path, e):
396 if isinstance(e, util.CommandException):
397 e_str = 'cmd: `{}`, code: `{}`, reason: `{}`'.format(e.cmd, e.code, e.reason)
398 else:
399 e_str = str(e)
401 try:
402 volume_uuid = self._linstor.get_volume_uuid_from_device_path(
403 device_path
404 )
405 e_wrapper = Exception(
406 e_str + ' (openers: {})'.format(
407 self._linstor.get_volume_openers(volume_uuid)
408 )
409 )
410 except Exception as illformed_e:
411 e_wrapper = Exception(
412 e_str + ' (unable to get openers: {})'.format(illformed_e)
413 )
414 util.SMlog('raise opener exception: {}'.format(e_wrapper))
415 raise e_wrapper # pylint: disable = E0702
417 def _call_local_method(self, local_method, device_path, *args, **kwargs):
418 if isinstance(local_method, str):
419 local_method = getattr(self, local_method)
421 try:
422 def local_call():
423 try:
424 return local_method(device_path, *args, **kwargs)
425 except util.CommandException as e:
426 if e.code == errno.EROFS or e.code == errno.EMEDIUMTYPE:
427 raise ErofsLinstorCallException(e) # Break retry calls.
428 if e.code == errno.ENOENT:
429 raise NoPathLinstorCallException(e)
430 raise e
431 # Retry only locally if it's not an EROFS exception.
432 return util.retry(local_call, 5, 2, exceptions=[util.CommandException])
433 except util.CommandException as e:
434 util.SMlog('failed to execute locally vhd-util (sys {})'.format(e.code))
435 raise e
437 def _call_local_method_or_fail(self, local_method, device_path, *args, **kwargs):
438 try:
439 return self._call_local_method(local_method, device_path, *args, **kwargs)
440 except ErofsLinstorCallException as e:
441 # Volume is locked on a host, find openers.
442 self._raise_openers_exception(device_path, e.cmd_err)
444 def _call_method(self, local_method, remote_method, device_path, use_parent, *args, **kwargs):
445 # Note: `use_parent` exists to know if the VHD parent is used by the local/remote method.
446 # Normally in case of failure, if the parent is unused we try to execute the method on
447 # another host using the DRBD opener list. In the other case, if the parent is required,
448 # we must check where this last one is open instead of the child.
450 if isinstance(local_method, str):
451 local_method = getattr(self, local_method)
453 # A. Try to write locally...
454 try:
455 return self._call_local_method(local_method, device_path, *args, **kwargs)
456 except Exception:
457 pass
459 util.SMlog('unable to execute `{}` locally, retry using a writable host...'.format(remote_method))
461 # B. Execute the command on another host.
462 # B.1. Get host list.
463 try:
464 hosts = self._session.xenapi.host.get_all_records()
465 except Exception as e:
466 raise xs_errors.XenError(
467 'VDIUnavailable',
468 opterr='Unable to get host list to run vhd-util command `{}` (path={}): {}'
469 .format(remote_method, device_path, e)
470 )
472 # B.2. Prepare remote args.
473 remote_args = {
474 'devicePath': device_path,
475 'groupName': self._linstor.group_name
476 }
477 remote_args.update(**kwargs)
478 remote_args = {str(key): str(value) for key, value in remote_args.items()}
480 volume_uuid = self._linstor.get_volume_uuid_from_device_path(
481 device_path
482 )
483 parent_volume_uuid = None
484 if use_parent:
485 parent_volume_uuid = self.get_parent(volume_uuid)
487 openers_uuid = parent_volume_uuid if use_parent else volume_uuid
489 # B.3. Call!
490 def remote_call():
491 try:
492 all_openers = self._linstor.get_volume_openers(openers_uuid)
493 except Exception as e:
494 raise xs_errors.XenError(
495 'VDIUnavailable',
496 opterr='Unable to get DRBD openers to run vhd-util command `{}` (path={}): {}'
497 .format(remote_method, device_path, e)
498 )
500 no_host_found = True
501 for hostname, openers in all_openers.items():
502 if not openers:
503 continue
505 try:
506 host_ref = next(ref for ref, rec in hosts.items() if rec['hostname'] == hostname)
507 except StopIteration:
508 continue
510 no_host_found = False
511 try:
512 return call_remote_method(self._session, host_ref, remote_method, device_path, remote_args)
513 except Exception:
514 pass
516 if no_host_found:
517 try:
518 return local_method(device_path, *args, **kwargs)
519 except Exception as e:
520 self._raise_openers_exception(device_path, e)
522 raise xs_errors.XenError(
523 'VDIUnavailable',
524 opterr='No valid host found to run vhd-util command `{}` (path=`{}`, openers=`{}`)'
525 .format(remote_method, device_path, openers)
526 )
527 return util.retry(remote_call, 5, 2)
529 @staticmethod
530 def _zeroize(path, size):
531 if not util.zeroOut(path, size, vhdutil.VHD_FOOTER_SIZE):
532 raise xs_errors.XenError(
533 'EIO',
534 opterr='Failed to zero out VHD footer {}'.format(path)
535 )