1 # Copyright (c) 2011, 2012 Nicira, Inc.
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:
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 util module contains some helper function
29 from six.moves import range
30 import six.moves.xmlrpc_client
33 def str_ip(ip_address):
35 Converts an IP address from binary format to a string.
37 (x1, x2, x3, x4) = struct.unpack("BBBB", ip_address)
38 return ("%u.%u.%u.%u") % (x1, x2, x3, x4)
41 def get_interface_mtu(iface):
43 Returns MTU of the given interface.
45 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
46 indata = iface + ('\0' * (32 - len(iface)))
48 outdata = fcntl.ioctl(s.fileno(), 0x8921, indata) # socket.SIOCGIFMTU
49 mtu = struct.unpack("16si12x", outdata)[1]
56 def get_interface(address):
58 Finds first interface that has given address
61 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
62 names = array.array('B', '\0' * bytes)
63 outbytes = struct.unpack('iL', fcntl.ioctl(
66 struct.pack('iL', bytes, names.buffer_info()[0])
68 namestr = names.tostring()
70 for i in range(0, outbytes, 40):
71 name = namestr[i:i + 16].split('\0', 1)[0]
72 if address == str_ip(namestr[i + 20:i + 24]):
74 return None # did not find interface we were looking for
79 return os_info[2] # return only the kernel version number
82 def start_process(args):
84 p = subprocess.Popen(args,
85 stdin=subprocess.PIPE,
86 stdout=subprocess.PIPE,
87 stderr=subprocess.PIPE)
88 out, err = p.communicate()
89 return (p.returncode, out, err)
90 except exceptions.OSError:
91 return (-1, None, None)
94 def get_driver(iface):
95 ret, out, _err = start_process(["ethtool", "-i", iface])
97 lines = out.splitlines()
98 driver = "%s(%s)" % (lines[0], lines[1]) # driver name + version
104 def interface_up(iface):
106 This function brings given iface up.
108 ret, _out, _err = start_process(["ifconfig", iface, "up"])
112 def interface_assign_ip(iface, ip_addr, mask):
114 This function allows to assign IP address to an interface. If mask is an
115 empty string then ifconfig will decide what kind of mask to use. The
116 caller can also specify the mask by using CIDR notation in ip argument by
117 leaving the mask argument as an empty string. In case of success this
120 args = ["ifconfig", iface, ip_addr]
122 args.append("netmask")
124 ret, _out, _err = start_process(args)
128 def interface_get_ip(iface):
130 This function returns tuple - ip and mask that was assigned to the
133 args = ["ifconfig", iface]
134 ret, out, _err = start_process(args)
137 ip = re.search(r'inet addr:(\S+)', out)
138 mask = re.search(r'Mask:(\S+)', out)
139 if ip is not None and mask is not None:
140 return (ip.group(1), mask.group(1))
145 def move_routes(iface1, iface2):
147 This function moves routes from iface1 to iface2.
149 args = ["ip", "route", "show", "dev", iface1]
150 ret, out, _err = start_process(args)
152 for route in out.splitlines():
153 args = ["ip", "route", "replace", "dev", iface2] + route.split()
157 def get_interface_from_routing_decision(ip):
159 This function returns the interface through which the given ip address
162 args = ["ip", "route", "get", ip]
163 ret, out, _err = start_process(args)
165 iface = re.search(r'dev (\S+)', out)
167 return iface.group(1)
171 def rpc_client(ip, port):
172 return six.moves.xmlrpc_client.Server("http://%s:%u/" % (ip, port),
176 def sigint_intercept():
178 Intercept SIGINT from child (the local ovs-test server process).
180 signal.signal(signal.SIGINT, signal.SIG_IGN)
183 def start_local_server(port):
185 This function spawns an ovs-test server that listens on specified port
186 and blocks till the spawned ovs-test server is ready to accept XML RPC
189 p = subprocess.Popen(["ovs-test", "-s", str(port)],
190 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
191 preexec_fn=sigint_intercept)
192 fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL,
193 fcntl.fcntl(p.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)
195 while p.poll() is None:
196 fd = select.select([p.stdout.fileno()], [], [])[0]
198 out = p.stdout.readline()
199 if out.startswith("Starting RPC server"):
201 if p.poll() is not None:
202 raise RuntimeError("Couldn't start local instance of ovs-test server")
206 def get_datagram_sizes(mtu1, mtu2):
208 This function calculates all the "interesting" datagram sizes so that
209 we test both - receive and send side with different packets sizes.
211 s1 = set([8, mtu1 - 100, mtu1 - 28, mtu1])
212 s2 = set([8, mtu2 - 100, mtu2 - 28, mtu2])
213 return sorted(s1.union(s2))
216 def ip_from_cidr(string):
218 This function removes the netmask (if present) from the given string and
219 returns the IP address.
221 token = string.split("/")
225 def bandwidth_to_string(bwidth):
226 """Convert bandwidth from long to string and add units."""
227 bwidth = bwidth * 8 # Convert back to bits/second
228 if bwidth >= 10000000:
229 return str(int(bwidth / 1000000)) + "Mbps"
231 return str(int(bwidth / 1000)) + "Kbps"
233 return str(int(bwidth)) + "bps"