blob: 7e6044d2bff51294757326bfc8b67137f94ece4a [file] [log] [blame]
Sreeju Sreedhare3fefd92019-04-02 15:57:15 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain 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,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
17
18"""
19Utilities for the OpenFlow test framework
20"""
21
22import random
23import time
24import os
25import fcntl
26import logging
27
28default_timeout = None # set by oft
29default_negative_timeout = None # set by oft
30
31def gen_xid():
32 return random.randrange(1,0xffffffff)
33
34"""
35Wait on a condition variable until the given function returns non-None or a timeout expires.
36The condition variable must already be acquired.
37The timeout value -1 means use the default timeout.
38There is deliberately no support for an infinite timeout.
39"""
40def timed_wait(cv, fn, timeout=-1):
41 if timeout == -1:
42 timeout = default_timeout
43
44 end_time = time.time() + timeout
45 while True:
46 val = fn()
47 if val != None:
48 return val
49
50 remaining_time = end_time - time.time()
51 cv.wait(remaining_time)
52
53 if time.time() > end_time:
54 return None
55
56class EventDescriptor():
57 """
58 Similar to a condition variable, but can be passed to select().
59 Only supports one waiter.
60 """
61
62 def __init__(self):
63 self.pipe_rd, self.pipe_wr = os.pipe()
64 fcntl.fcntl(self.pipe_wr, fcntl.F_SETFL, os.O_NONBLOCK)
65
66 def __del__(self):
67 os.close(self.pipe_rd)
68 os.close(self.pipe_wr)
69
70 def notify(self):
71 try:
72 os.write(self.pipe_wr, "x")
73 except OSError as e:
74 logging.warn("Failed to notify EventDescriptor: %s", e)
75
76 def wait(self):
77 os.read(self.pipe_rd, 1)
78
79 def fileno(self):
80 return self.pipe_rd