ofp-actions: Fix use-after-free in bundle action.
[cascardo/ovs.git] / python / ovs / timeval.py
1 # Copyright (c) 2009, 2010 Nicira, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import sys
16 import time
17
18 try:
19     import ctypes
20
21     LIBRT = 'librt.so.1'
22     clock_gettime_name = 'clock_gettime'
23
24     if sys.platform.startswith("linux"):
25         CLOCK_MONOTONIC = 1
26         time_t = ctypes.c_long
27     elif sys.platform.startswith("netbsd"):
28         # NetBSD uses function renaming for ABI versioning.  While the proper
29         # way to get the appropriate version is of course "#include <time.h>",
30         # it is difficult with ctypes.  The following is appropriate for
31         # recent versions of NetBSD, including NetBSD-6.
32         LIBRT = 'libc.so.12'
33         clock_gettime_name = '__clock_gettime50'
34         CLOCK_MONOTONIC = 3
35         time_t = ctypes.c_int64
36     elif sys.platform.startswith("freebsd"):
37         CLOCK_MONOTONIC = 4
38         time_t = ctypes.c_int64
39     else:
40         raise Exception
41
42     class timespec(ctypes.Structure):
43         _fields_ = [
44             ('tv_sec', time_t),
45             ('tv_nsec', ctypes.c_long),
46         ]
47
48     librt = ctypes.CDLL(LIBRT)
49     clock_gettime = getattr(librt, clock_gettime_name)
50     clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
51 except:
52     # Librt shared library could not be loaded
53     librt = None
54
55
56 def monotonic():
57     if not librt:
58         return time.time()
59
60     t = timespec()
61     if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(t)) == 0:
62         return t.tv_sec + t.tv_nsec * 1e-9
63     # Kernel does not support CLOCK_MONOTONIC
64     return time.time()
65
66
67 # Use time.monotonic() if Python version >= 3.3
68 if not hasattr(time, 'monotonic'):
69     time.monotonic = monotonic
70
71
72 def msec():
73     """ Returns the system's monotonic time if possible, otherwise returns the
74     current time as the amount of time since the epoch, in milliseconds, as a
75     float."""
76     return time.monotonic() * 1000.0
77
78
79 def postfork():
80     # Just a stub for now
81     pass