blob: 8cf2ae00fe83faa98ec19a0d819ce4e3b4b54b42 [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
Rich Lane4dfd5e12012-12-22 19:48:01 -08008import os
Rich Lane7e1d5c52012-12-24 14:08:32 -08009import fcntl
Rich Lane2e37ec22012-12-26 09:47:39 -080010import logging
Dan Talaycoea8ad802010-02-22 20:30:18 -080011
Rich Lanee55abf72012-07-26 20:11:42 -070012default_timeout = None # set by oft
13
Dan Talaycoea8ad802010-02-22 20:30:18 -080014def gen_xid():
15 return random.randrange(1,0xffffffff)
Rich Laneb64ce3d2012-07-26 15:37:57 -070016
17"""
18Wait on a condition variable until the given function returns non-None or a timeout expires.
19The condition variable must already be acquired.
Rich Lane8806bc42012-07-26 19:18:37 -070020The timeout value -1 means use the default timeout.
Rich Laneb64ce3d2012-07-26 15:37:57 -070021There is deliberately no support for an infinite timeout.
22TODO: get the default timeout from configuration
23"""
Rich Lane8806bc42012-07-26 19:18:37 -070024def timed_wait(cv, fn, timeout=-1):
25 if timeout == -1:
26 # TODO make this configurable
Rich Lanee55abf72012-07-26 20:11:42 -070027 timeout = default_timeout
Rich Lane8806bc42012-07-26 19:18:37 -070028
Rich Laneb64ce3d2012-07-26 15:37:57 -070029 end_time = time.time() + timeout
30 while True:
Rich Laneb64ce3d2012-07-26 15:37:57 -070031 val = fn()
32 if val != None:
33 return val
34
35 remaining_time = end_time - time.time()
36 cv.wait(remaining_time)
Rich Lane8806bc42012-07-26 19:18:37 -070037
38 if time.time() > end_time:
39 return None
Rich Lane4dfd5e12012-12-22 19:48:01 -080040
41class EventDescriptor():
42 """
43 Similar to a condition variable, but can be passed to select().
44 Only supports one waiter.
45 """
46
47 def __init__(self):
48 self.pipe_rd, self.pipe_wr = os.pipe()
Rich Lane7e1d5c52012-12-24 14:08:32 -080049 fcntl.fcntl(self.pipe_wr, fcntl.F_SETFL, os.O_NONBLOCK)
Rich Lane4dfd5e12012-12-22 19:48:01 -080050
51 def __del__(self):
52 os.close(self.pipe_rd)
53 os.close(self.pipe_wr)
54
55 def notify(self):
Rich Lane7e1d5c52012-12-24 14:08:32 -080056 try:
57 os.write(self.pipe_wr, "x")
58 except OSError as e:
Rich Lane2e37ec22012-12-26 09:47:39 -080059 logging.warn("Failed to notify EventDescriptor: %s", e)
Rich Lane4dfd5e12012-12-22 19:48:01 -080060
61 def wait(self):
62 os.read(self.pipe_rd, 1)
63
64 def fileno(self):
65 return self.pipe_rd