From 05bd946cad9ab369741fffa7c2e978a0bb074cb5 Mon Sep 17 00:00:00 2001 From: Leonid Usov Date: Thu, 4 Jan 2024 19:51:32 +0200 Subject: [PATCH] mgr/volumes: use `volume_exception_to_retval` as a decorator When used as a decorator, it saves one indented try-catch block inside the decorated method. This can be applied to most of the methods in the file, subject to a separate refactoring commit Signed-off-by: Leonid Usov (cherry picked from commit 78afc6136118e14e2cf6a5651bfe11777c9881a4) --- src/pybind/mgr/volumes/fs/volume.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/pybind/mgr/volumes/fs/volume.py b/src/pybind/mgr/volumes/fs/volume.py index c896fd73d0b05..d238a4daf2c55 100644 --- a/src/pybind/mgr/volumes/fs/volume.py +++ b/src/pybind/mgr/volumes/fs/volume.py @@ -2,7 +2,9 @@ import json import errno import logging import mgr_util -from typing import TYPE_CHECKING +import inspect +import functools +from typing import TYPE_CHECKING, Any, Callable, Optional import cephfs @@ -83,11 +85,28 @@ class VolumeClient(CephfsClient["Module"]): lvl = self.mgr.ClusterLogPrio.WARN self.mgr.cluster_log("cluster", lvl, msg) - def volume_exception_to_retval(self, ve): + def volume_exception_to_retval(self_or_method: Any, ve: Optional[VolumeException] = None): """ return a tuple representation from a volume exception + OR wrap the decorated method into a try:catch: + that will convert VolumeException to the tuple """ - return ve.to_tuple() + if ve is None and callable(self_or_method): + # used as a decorator + method: Callable = self_or_method + @functools.wraps(method) + def wrapper(self, *args, **kwargs): + try: + return method(self, *args, **kwargs) + except VolumeException as ve: + return self.volume_exception_to_retval(ve) + return wrapper + elif ve is not None: + # used as a method on self with a VolumeException argument + return ve.to_tuple() + else: + # shouldn't get here, bad call + assert(ve is not None) ### volume operations -- create, rm, ls -- 2.39.5