python: Fix xmlrpclib imports.
[cascardo/ovs.git] / python / ovstest / util.py
1 # Copyright (c) 2011, 2012 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 """
16 util module contains some helper function
17 """
18 import array
19 import exceptions
20 import fcntl
21 import os
22 import select
23 import socket
24 import struct
25 import signal
26 import subprocess
27 import re
28
29 import six.moves.xmlrpc_client
30
31
32 def str_ip(ip_address):
33     """
34     Converts an IP address from binary format to a string.
35     """
36     (x1, x2, x3, x4) = struct.unpack("BBBB", ip_address)
37     return ("%u.%u.%u.%u") % (x1, x2, x3, x4)
38
39
40 def get_interface_mtu(iface):
41     """
42     Returns MTU of the given interface.
43     """
44     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
45     indata = iface + ('\0' * (32 - len(iface)))
46     try:
47         outdata = fcntl.ioctl(s.fileno(), 0x8921, indata)  # socket.SIOCGIFMTU
48         mtu = struct.unpack("16si12x", outdata)[1]
49     except:
50         return 0
51
52     return mtu
53
54
55 def get_interface(address):
56     """
57     Finds first interface that has given address
58     """
59     bytes = 256 * 32
60     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
61     names = array.array('B', '\0' * bytes)
62     outbytes = struct.unpack('iL', fcntl.ioctl(
63         s.fileno(),
64         0x8912,  # SIOCGIFCONF
65         struct.pack('iL', bytes, names.buffer_info()[0])
66     ))[0]
67     namestr = names.tostring()
68
69     for i in range(0, outbytes, 40):
70         name = namestr[i:i + 16].split('\0', 1)[0]
71         if address == str_ip(namestr[i + 20:i + 24]):
72             return name
73     return None  # did not find interface we were looking for
74
75
76 def uname():
77     os_info = os.uname()
78     return os_info[2]  # return only the kernel version number
79
80
81 def start_process(args):
82     try:
83         p = subprocess.Popen(args,
84                              stdin=subprocess.PIPE,
85                              stdout=subprocess.PIPE,
86                              stderr=subprocess.PIPE)
87         out, err = p.communicate()
88         return (p.returncode, out, err)
89     except exceptions.OSError:
90         return (-1, None, None)
91
92
93 def get_driver(iface):
94     ret, out, _err = start_process(["ethtool", "-i", iface])
95     if ret == 0:
96         lines = out.splitlines()
97         driver = "%s(%s)" % (lines[0], lines[1])  # driver name + version
98     else:
99         driver = None
100     return driver
101
102
103 def interface_up(iface):
104     """
105     This function brings given iface up.
106     """
107     ret, _out, _err = start_process(["ifconfig", iface, "up"])
108     return ret
109
110
111 def interface_assign_ip(iface, ip_addr, mask):
112     """
113     This function allows to assign IP address to an interface. If mask is an
114     empty string then ifconfig will decide what kind of mask to use. The
115     caller can also specify the mask by using CIDR notation in ip argument by
116     leaving the mask argument as an empty string. In case of success this
117     function returns 0.
118     """
119     args = ["ifconfig", iface, ip_addr]
120     if mask is not None:
121         args.append("netmask")
122         args.append(mask)
123     ret, _out, _err = start_process(args)
124     return ret
125
126
127 def interface_get_ip(iface):
128     """
129     This function returns tuple - ip and mask that was assigned to the
130     interface.
131     """
132     args = ["ifconfig", iface]
133     ret, out, _err = start_process(args)
134
135     if ret == 0:
136         ip = re.search(r'inet addr:(\S+)', out)
137         mask = re.search(r'Mask:(\S+)', out)
138         if ip is not None and mask is not None:
139             return (ip.group(1), mask.group(1))
140     else:
141         return ret
142
143
144 def move_routes(iface1, iface2):
145     """
146     This function moves routes from iface1 to iface2.
147     """
148     args = ["ip", "route", "show", "dev", iface1]
149     ret, out, _err = start_process(args)
150     if ret == 0:
151         for route in out.splitlines():
152             args = ["ip", "route", "replace", "dev", iface2] + route.split()
153             start_process(args)
154
155
156 def get_interface_from_routing_decision(ip):
157     """
158     This function returns the interface through which the given ip address
159     is reachable.
160     """
161     args = ["ip", "route", "get", ip]
162     ret, out, _err = start_process(args)
163     if ret == 0:
164         iface = re.search(r'dev (\S+)', out)
165         if iface:
166             return iface.group(1)
167     return None
168
169
170 def rpc_client(ip, port):
171     return six.moves.xmlrpc_client.Server("http://%s:%u/" % (ip, port),
172                                           allow_none=True)
173
174
175 def sigint_intercept():
176     """
177     Intercept SIGINT from child (the local ovs-test server process).
178     """
179     signal.signal(signal.SIGINT, signal.SIG_IGN)
180
181
182 def start_local_server(port):
183     """
184     This function spawns an ovs-test server that listens on specified port
185     and blocks till the spawned ovs-test server is ready to accept XML RPC
186     connections.
187     """
188     p = subprocess.Popen(["ovs-test", "-s", str(port)],
189                          stdout=subprocess.PIPE, stderr=subprocess.PIPE,
190                          preexec_fn=sigint_intercept)
191     fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL,
192         fcntl.fcntl(p.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)
193
194     while p.poll() is None:
195         fd = select.select([p.stdout.fileno()], [], [])[0]
196         if fd:
197             out = p.stdout.readline()
198             if out.startswith("Starting RPC server"):
199                 break
200     if p.poll() is not None:
201         raise RuntimeError("Couldn't start local instance of ovs-test server")
202     return p
203
204
205 def get_datagram_sizes(mtu1, mtu2):
206     """
207     This function calculates all the "interesting" datagram sizes so that
208     we test both - receive and send side with different packets sizes.
209     """
210     s1 = set([8, mtu1 - 100, mtu1 - 28, mtu1])
211     s2 = set([8, mtu2 - 100, mtu2 - 28, mtu2])
212     return sorted(s1.union(s2))
213
214
215 def ip_from_cidr(string):
216     """
217     This function removes the netmask (if present) from the given string and
218     returns the IP address.
219     """
220     token = string.split("/")
221     return token[0]
222
223
224 def bandwidth_to_string(bwidth):
225     """Convert bandwidth from long to string and add units."""
226     bwidth = bwidth * 8  # Convert back to bits/second
227     if bwidth >= 10000000:
228         return str(int(bwidth / 1000000)) + "Mbps"
229     elif bwidth > 10000:
230         return str(int(bwidth / 1000)) + "Kbps"
231     else:
232         return str(int(bwidth)) + "bps"