Chandan Kumar | 5e61987 | 2017-09-07 22:23:55 +0530 | [diff] [blame^] | 1 | # 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 | |
| 21 | import threading |
| 22 | import eventlet |
| 23 | |
| 24 | class classproperty(object): |
| 25 | def __init__(self, f): |
| 26 | self.func = f |
| 27 | |
| 28 | def __get__(self, obj, owner): |
| 29 | return self.func(owner) |
| 30 | |
| 31 | class WaitTimeout(Exception): |
| 32 | """Default exception coming from wait_until_true() function.""" |
| 33 | |
| 34 | |
| 35 | class LockWithTimer(object): |
| 36 | def __init__(self, threshold): |
| 37 | self._threshold = threshold |
| 38 | self.timestamp = 0 |
| 39 | self._lock = threading.Lock() |
| 40 | |
| 41 | def acquire(self): |
| 42 | return self._lock.acquire(False) |
| 43 | |
| 44 | def release(self): |
| 45 | return self._lock.release() |
| 46 | |
| 47 | def time_to_wait(self): |
| 48 | return self.timestamp - time.time() + self._threshold |
| 49 | |
| 50 | def wait_until_true(predicate, timeout=60, sleep=1, exception=None): |
| 51 | """ |
| 52 | Wait until callable predicate is evaluated as True |
| 53 | :param predicate: Callable deciding whether waiting should continue. |
| 54 | Best practice is to instantiate predicate with functools.partial() |
| 55 | :param timeout: Timeout in seconds how long should function wait. |
| 56 | :param sleep: Polling interval for results in seconds. |
| 57 | :param exception: Exception instance to raise on timeout. If None is passed |
| 58 | (default) then WaitTimeout exception is raised. |
| 59 | """ |
| 60 | try: |
| 61 | with eventlet.Timeout(timeout): |
| 62 | while not predicate(): |
| 63 | eventlet.sleep(sleep) |
| 64 | except eventlet.Timeout: |
| 65 | if exception is not None: |
| 66 | #pylint: disable=raising-bad-type |
| 67 | raise exception |
| 68 | raise WaitTimeout("Timed out after %d seconds" % timeout) |