Dan Talayco | ea8ad80 | 2010-02-22 20:30:18 -0800 | [diff] [blame] | 1 | |
| 2 | """ |
| 3 | Utilities for the OpenFlow test framework |
| 4 | """ |
| 5 | |
| 6 | import random |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 7 | import time |
Dan Talayco | ea8ad80 | 2010-02-22 20:30:18 -0800 | [diff] [blame] | 8 | |
Rich Lane | e55abf7 | 2012-07-26 20:11:42 -0700 | [diff] [blame^] | 9 | default_timeout = None # set by oft |
| 10 | |
Dan Talayco | ea8ad80 | 2010-02-22 20:30:18 -0800 | [diff] [blame] | 11 | def gen_xid(): |
| 12 | return random.randrange(1,0xffffffff) |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 13 | |
| 14 | """ |
| 15 | Wait on a condition variable until the given function returns non-None or a timeout expires. |
| 16 | The condition variable must already be acquired. |
Rich Lane | 8806bc4 | 2012-07-26 19:18:37 -0700 | [diff] [blame] | 17 | The timeout value -1 means use the default timeout. |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 18 | There is deliberately no support for an infinite timeout. |
| 19 | TODO: get the default timeout from configuration |
| 20 | """ |
Rich Lane | 8806bc4 | 2012-07-26 19:18:37 -0700 | [diff] [blame] | 21 | def timed_wait(cv, fn, timeout=-1): |
| 22 | if timeout == -1: |
| 23 | # TODO make this configurable |
Rich Lane | e55abf7 | 2012-07-26 20:11:42 -0700 | [diff] [blame^] | 24 | timeout = default_timeout |
Rich Lane | 8806bc4 | 2012-07-26 19:18:37 -0700 | [diff] [blame] | 25 | |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 26 | end_time = time.time() + timeout |
| 27 | while True: |
Rich Lane | b64ce3d | 2012-07-26 15:37:57 -0700 | [diff] [blame] | 28 | val = fn() |
| 29 | if val != None: |
| 30 | return val |
| 31 | |
| 32 | remaining_time = end_time - time.time() |
| 33 | cv.wait(remaining_time) |
Rich Lane | 8806bc4 | 2012-07-26 19:18:37 -0700 | [diff] [blame] | 34 | |
| 35 | if time.time() > end_time: |
| 36 | return None |