ovs-test: A new tool that allows to diagnose connectivity and performance issues
[cascardo/ovs.git] / python / ovstest / util.py
1 # Copyright (c) 2011 Nicira Networks
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 socket, struct, fcntl, array, os, subprocess, exceptions
19
20 def str_ip(ip):
21     (x1, x2, x3, x4) = struct.unpack("BBBB", ip)
22     return ("%u.%u.%u.%u") % (x1, x2, x3, x4)
23
24 def get_interface_mtu(iface):
25     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
26     indata = iface + ('\0' * (32 - len(iface)))
27     try:
28         outdata = fcntl.ioctl(s.fileno(), 0x8921, indata) #  socket.SIOCGIFMTU
29         mtu = struct.unpack("16si12x", outdata)[1]
30     except:
31         return 0
32
33     return mtu
34
35 def get_interface(address):
36     """
37     Finds first interface that has given address
38     """
39     bytes = 256 * 32
40     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
41     names = array.array('B', '\0' * bytes)
42     outbytes = struct.unpack('iL', fcntl.ioctl(
43         s.fileno(),
44         0x8912, # SIOCGIFCONF
45         struct.pack('iL', bytes, names.buffer_info()[0])
46     ))[0]
47     namestr = names.tostring()
48
49     for i in range(0, outbytes, 40):
50         name = namestr[i:i + 16].split('\0', 1)[0]
51         if address == str_ip(namestr[i + 20:i + 24]):
52             return name
53     return "" #  did not find interface we were looking for
54
55 def uname():
56     os_info = os.uname()
57     return os_info[2] #return only the kernel version number
58
59 def get_driver(iface):
60     try:
61         p = subprocess.Popen(
62             ["ethtool", "-i", iface],
63             stdin = subprocess.PIPE,
64             stdout = subprocess.PIPE,
65             stderr = subprocess.PIPE)
66         out, err = p.communicate()
67         if p.returncode == 0:
68             lines = out.split("\n")
69             driver = "%s(%s)" % (lines[0], lines[1]) #driver name + version
70         else:
71             driver = "no support for ethtool"
72     except exceptions.OSError:
73         driver = ""
74     return driver