]> git-server-git.apps.pok.os.sepia.ceph.com Git - ceph.git/commitdiff
mgr/diskprediction_cloud: refactor timeout() decorator 31176/head
authorKefu Chai <kchai@redhat.com>
Sun, 27 Oct 2019 02:00:01 +0000 (10:00 +0800)
committerKefu Chai <kchai@redhat.com>
Sun, 27 Oct 2019 02:15:09 +0000 (10:15 +0800)
* timeout() is never passed any parameter when being called, so let's
  remove the parameters list of "seconds" and "error_message"
* use `getattr()` instead of `hasattr()` for retrieving the
  member variable of `self`
* pass `self` to wrapper function explicitly.
* return `func()` right away.
* hardwire the error message of `TimeoutError` to "Timer expired",
  because
  - as neither errno.ETIME nor errno.ETIMEOUT is portable
  - the only caller of `TimeoutError` is `timeout()`, so there is
    no need to have the flexibility to pass a different error message
* use `wraps()` as a decorator, simpler this way.

Signed-off-by: Kefu Chai <kchai@redhat.com>
src/pybind/mgr/diskprediction_cloud/agent/__init__.py
src/pybind/mgr/diskprediction_cloud/common/__init__.py

index c7702e5242c86d57d9a4406f37855122ae63c676..e7e0ddcb6ed3e3f523446d1b947ad0509912d33a 100644 (file)
@@ -29,10 +29,10 @@ class BaseAgent(object):
         else:\r
             return True\r
 \r
-    @timeout()\r
+    @timeout\r
     def _run(self):\r
         pass\r
 \r
-    @timeout()\r
+    @timeout\r
     def _collect_data(self):\r
         pass\r
index ce5131b8f2b906a749717e7b6be1b41930d6596d..be40941663925167fb7dd394d2c2d5f2d6122052 100644 (file)
@@ -26,28 +26,26 @@ class DummyResonse:
 \r
 \r
 class TimeoutError(Exception):\r
-    pass\r
+    def __init__(self):\r
+        super(TimeoutError, self).__init__("Timer expired")\r
 \r
 \r
-def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):\r
-    def decorator(func):\r
-        def _handle_timeout(signum, frame):\r
-            raise TimeoutError(error_message)\r
+def timeout(func):\r
+    DEFAULT_TIMEOUT = 10\r
 \r
-        def wrapper(*args, **kwargs):\r
-            if hasattr(args[0], '_timeout') is not None:\r
-                seconds = args[0]._timeout\r
-            signal.signal(signal.SIGALRM, _handle_timeout)\r
-            signal.alarm(seconds)\r
-            try:\r
-                result = func(*args, **kwargs)\r
-            finally:\r
-                signal.alarm(0)\r
-            return result\r
+    def _handle_timeout(signum, frame):\r
+        raise TimeoutError()\r
 \r
-        return wraps(func)(wrapper)\r
+    @wraps(func)\r
+    def wrapper(self):\r
+        signal.signal(signal.SIGALRM, _handle_timeout)\r
+        signal.alarm(getattr(self, '_timeout', DEFAULT_TIMEOUT))\r
+        try:\r
+            return func(self)\r
+        finally:\r
+            signal.alarm(0)\r
 \r
-    return decorator\r
+    return wrapper\r
 \r
 \r
 def get_human_readable(size, precision=2):\r