blob: ecccd1875c3b3cc48e14a59f61938f018ef1a805 [file] [log] [blame]
Chandan Kumar5e619872017-09-07 22:23:55 +05301# Copyright 2011, VMware, Inc.
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15#
16# Borrowed from nova code base, more utilities will be added/borrowed as and
17# when needed.
18
19"""Utilities and helper functions."""
20
Chandan Kumar5e619872017-09-07 22:23:55 +053021import eventlet
Chandan Kumar667d3d32017-09-22 12:24:06 +053022import threading
23import time
24
Chandan Kumar5e619872017-09-07 22:23:55 +053025
26class classproperty(object):
27 def __init__(self, f):
28 self.func = f
29
30 def __get__(self, obj, owner):
Chandan Kumar667d3d32017-09-22 12:24:06 +053031 return self.func(owner)
32
Chandan Kumar5e619872017-09-07 22:23:55 +053033
34class WaitTimeout(Exception):
35 """Default exception coming from wait_until_true() function."""
36
37
38class LockWithTimer(object):
39 def __init__(self, threshold):
40 self._threshold = threshold
41 self.timestamp = 0
42 self._lock = threading.Lock()
43
44 def acquire(self):
45 return self._lock.acquire(False)
46
47 def release(self):
48 return self._lock.release()
49
50 def time_to_wait(self):
51 return self.timestamp - time.time() + self._threshold
52
Chandan Kumar667d3d32017-09-22 12:24:06 +053053
Chandan Kumar5e619872017-09-07 22:23:55 +053054def wait_until_true(predicate, timeout=60, sleep=1, exception=None):
55 """
56 Wait until callable predicate is evaluated as True
57 :param predicate: Callable deciding whether waiting should continue.
58 Best practice is to instantiate predicate with functools.partial()
59 :param timeout: Timeout in seconds how long should function wait.
60 :param sleep: Polling interval for results in seconds.
61 :param exception: Exception instance to raise on timeout. If None is passed
62 (default) then WaitTimeout exception is raised.
63 """
64 try:
65 with eventlet.Timeout(timeout):
66 while not predicate():
67 eventlet.sleep(sleep)
68 except eventlet.Timeout:
69 if exception is not None:
70 #pylint: disable=raising-bad-type
71 raise exception
72 raise WaitTimeout("Timed out after %d seconds" % timeout)