1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
11 from StringIO import StringIO
15 LOG = logging.getLogger(__name__)
18 def call(cmd, shell=False):
22 LOG.info(' '.join(cmd))
23 return subprocess.call(cmd, shell=shell)
26 def check_call(cmd, shell=False):
30 LOG.info(' '.join(cmd))
31 subprocess.check_call(cmd, shell=shell)
34 def check_output(cmd, shell=False):
38 LOG.info(' '.join(cmd))
39 return subprocess.check_output(cmd, shell=shell)
42 def check_and_kill(process):
43 cmd = "ps -ef | grep -v grep | awk '{print $8}' | grep -w %s | wc -l" % process
44 out = check_output(cmd, shell=True)
46 check_call(['killall', process])
49 def check_and_rmmod(mod):
50 cmd = "lsmod | awk '{print $1}' | grep -w %s | wc -l" % mod
51 out = check_output(cmd, shell=True)
53 check_call(['rmmod', mod])
57 mount_path_set = set()
58 out = check_output("cat /proc/mounts", shell=True)
64 mpath = line.split()[1]
65 mount_path_set.add(mpath)
66 if path in mount_path_set:
67 ret = call("umount %s" % path, shell=True)
72 class IPCommandHelper(object):
77 self.device_mac_map = {}
78 self.mac_device_map = {}
79 self.bdf_device_map = {}
80 self.device_bdf_map = {}
83 buf = check_output("ip link", shell=True)
85 "[A-F0-9]{2}(?::[A-F0-9]{2}){5}",
86 re.IGNORECASE | re.MULTILINE)
87 for mac in macs.findall(buf):
88 if mac.lower() in ('00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff'):
93 m = re.match(r'^\d+:(.*):.*', line)
94 if m and m.group(1).strip() != 'lo':
95 self.devices.append(m.group(1).strip())
96 for device, mac in zip(self.devices, self.macs):
97 self.device_mac_map[device] = mac
98 self.mac_device_map[mac] = device
99 for device in self.devices:
100 buf = check_output("ethtool -i %s" % device, shell=True)
102 r'^bus-info: \d{4}:(\d{2}:\d{2}\.\d*)$',
106 self.bdf_device_map[bdfs[0]] = device
107 self.device_bdf_map[device] = bdfs[0]
108 mac = self.device_mac_map[device]
109 self.mac_bdf_map[mac] = bdfs[0]
110 self.bdf_mac_map[bdfs[0]] = mac
113 if __name__ == '__main__':
114 ip_helper = IPCommandHelper()
115 print ip_helper.device_mac_map
116 print ip_helper.mac_device_map
117 print ip_helper.bdf_device_map
118 print ip_helper.device_bdf_map
119 print ip_helper.mac_bdf_map
120 print ip_helper.bdf_mac_map