Sreeju Sreedhar | e3fefd9 | 2019-04-02 15:57:15 -0700 | [diff] [blame] | 1 | |
| 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 | """ |
| 19 | Utilities for the OpenFlow test framework |
| 20 | """ |
| 21 | |
| 22 | import random |
| 23 | import time |
| 24 | import os |
| 25 | import fcntl |
| 26 | import logging |
| 27 | |
| 28 | default_timeout = None # set by oft |
| 29 | default_negative_timeout = None # set by oft |
| 30 | |
| 31 | def gen_xid(): |
| 32 | return random.randrange(1,0xffffffff) |
| 33 | |
| 34 | """ |
| 35 | Wait on a condition variable until the given function returns non-None or a timeout expires. |
| 36 | The condition variable must already be acquired. |
| 37 | The timeout value -1 means use the default timeout. |
| 38 | There is deliberately no support for an infinite timeout. |
| 39 | """ |
| 40 | def 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 | |
| 56 | class 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 |