Global replace of Nicira Networks.
[sliver-openvswitch.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 socket
23 import struct
24 import subprocess
25 import re
26
27
28 def str_ip(ip_address):
29     """
30     Converts an IP address from binary format to a string.
31     """
32     (x1, x2, x3, x4) = struct.unpack("BBBB", ip_address)
33     return ("%u.%u.%u.%u") % (x1, x2, x3, x4)
34
35
36 def get_interface_mtu(iface):
37     """
38     Returns MTU of the given interface.
39     """
40     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
41     indata = iface + ('\0' * (32 - len(iface)))
42     try:
43         outdata = fcntl.ioctl(s.fileno(), 0x8921, indata) #  socket.SIOCGIFMTU
44         mtu = struct.unpack("16si12x", outdata)[1]
45     except:
46         return 0
47
48     return mtu
49
50
51 def get_interface(address):
52     """
53     Finds first interface that has given address
54     """
55     bytes = 256 * 32
56     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
57     names = array.array('B', '\0' * bytes)
58     outbytes = struct.unpack('iL', fcntl.ioctl(
59         s.fileno(),
60         0x8912, # SIOCGIFCONF
61         struct.pack('iL', bytes, names.buffer_info()[0])
62     ))[0]
63     namestr = names.tostring()
64
65     for i in range(0, outbytes, 40):
66         name = namestr[i:i + 16].split('\0', 1)[0]
67         if address == str_ip(namestr[i + 20:i + 24]):
68             return name
69     return None  # did not find interface we were looking for
70
71
72 def uname():
73     os_info = os.uname()
74     return os_info[2]  # return only the kernel version number
75
76
77 def start_process(args):
78     try:
79         p = subprocess.Popen(args,
80             stdin = subprocess.PIPE,
81             stdout = subprocess.PIPE,
82             stderr = subprocess.PIPE)
83         out, err = p.communicate()
84         return (p.returncode, out, err)
85     except exceptions.OSError:
86         return (-1, None, None)
87
88
89 def get_driver(iface):
90     ret, out, _err = start_process(["ethtool", "-i", iface])
91     if ret == 0:
92         lines = out.splitlines()
93         driver = "%s(%s)" % (lines[0], lines[1])  # driver name + version
94     else:
95         driver = None
96     return driver
97
98
99 def interface_up(iface):
100     """
101     This function brings given iface up.
102     """
103     ret, _out, _err = start_process(["ifconfig", iface, "up"])
104     return ret
105
106
107 def interface_assign_ip(iface, ip_addr, mask):
108     """
109     This function allows to assign IP address to an interface. If mask is an
110     empty string then ifconfig will decide what kind of mask to use. The
111     caller can also specify the mask by using CIDR notation in ip argument by
112     leaving the mask argument as an empty string. In case of success this
113     function returns 0.
114     """
115     args = ["ifconfig", iface, ip_addr]
116     if mask is not None:
117         args.append("netmask")
118         args.append(mask)
119     ret, _out, _err = start_process(args)
120     return ret
121
122
123 def interface_get_ip(iface):
124     """
125     This function returns tuple - ip and mask that was assigned to the
126     interface.
127     """
128     args = ["ifconfig", iface]
129     ret, out, _err = start_process(args)
130
131     if ret == 0:
132         ip = re.search(r'inet addr:(\S+)', out)
133         mask = re.search(r'Mask:(\S+)', out)
134         if ip is not None and mask is not None:
135             return (ip.group(1), mask.group(1))
136     else:
137         return ret
138
139
140 def move_routes(iface1, iface2):
141     """
142     This function moves routes from iface1 to iface2.
143     """
144     args = ["ip", "route", "show", "dev", iface1]
145     ret, out, _err = start_process(args)
146     if ret == 0:
147         for route in out.splitlines():
148             args = ["ip", "route", "replace", "dev", iface2] + route.split()
149             start_process(args)