blob: ce4e6ad478aea8664c064d3d5b8023d852283fc1 [file] [log] [blame]
Dan Talaycoea8ad802010-02-22 20:30:18 -08001
2"""
3Utilities for the OpenFlow test framework
4"""
5
6import random
Rich Laneb64ce3d2012-07-26 15:37:57 -07007import time
Dan Talaycoea8ad802010-02-22 20:30:18 -08008
9def gen_xid():
10 return random.randrange(1,0xffffffff)
Rich Laneb64ce3d2012-07-26 15:37:57 -070011
12"""
13Wait on a condition variable until the given function returns non-None or a timeout expires.
14The condition variable must already be acquired.
Rich Lane8806bc42012-07-26 19:18:37 -070015The timeout value -1 means use the default timeout.
Rich Laneb64ce3d2012-07-26 15:37:57 -070016There is deliberately no support for an infinite timeout.
17TODO: get the default timeout from configuration
18"""
Rich Lane8806bc42012-07-26 19:18:37 -070019def timed_wait(cv, fn, timeout=-1):
20 if timeout == -1:
21 # TODO make this configurable
Rich Lanec8aaa3e2012-07-26 19:28:02 -070022 timeout = 2
Rich Lane8806bc42012-07-26 19:18:37 -070023
Rich Laneb64ce3d2012-07-26 15:37:57 -070024 end_time = time.time() + timeout
25 while True:
Rich Laneb64ce3d2012-07-26 15:37:57 -070026 val = fn()
27 if val != None:
28 return val
29
30 remaining_time = end_time - time.time()
31 cv.wait(remaining_time)
Rich Lane8806bc42012-07-26 19:18:37 -070032
33 if time.time() > end_time:
34 return None