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 vstf.common.utils import IPCommandHelper
12 from vstf.agent.perf import ethtool
13 from vstf.common.utils import check_call, check_output, ns_cmd, my_popen, my_sleep
15 LOG = logging.getLogger(__name__)
21 super(Netns, self).__init__()
22 self.netns_add_str = "ip netns add %s"
23 self.netns_del_str = " ip netns del %s"
24 self.netns_add_device_str = " ip link set %s netns %s"
25 self.set_link_up_str = "ip link set dev %s up"
26 self.set_link_addr_str = "ip addr replace %s dev %s"
27 self.netns_remove_device_str = "ip netns exec %s ip link set %s netns 1"
28 # self.set_link_addr_str = "ifconfig %s %s up"
31 def clean_all_namespace(self):
32 out = check_output("ip netns list", shell=True)
33 for ns in out.splitlines():
34 self.remove_namespace(ns)
37 def create_namespace(self, name):
38 if name in (None, 'None', 'none'):
40 cmd = self.netns_add_str % name
41 check_call(cmd, shell=True)
44 def remove_namespace(self, ns):
45 if ns in (None, 'None', 'none'):
47 ip_helper = IPCommandHelper(ns)
48 for dev in ip_helper.device_mac_map:
49 cmd = self.netns_remove_device_str % (ns, dev)
50 check_call(cmd, shell=True)
51 self.activate_device(None, dev)
52 cmd = self.netns_del_str % ns
53 check_call(cmd, shell=True)
56 def add_device(self, ns, device):
59 cmd = self.netns_add_device_str % (device, ns)
60 check_call(cmd, shell=True)
63 def config_ip(self, ns, device, ip):
64 self.activate_device(ns, device)
65 cmd = self.set_link_addr_str % (ip, device)
67 check_call(cmd, shell=True)
70 def activate_device(self, ns, device):
71 cmd = self.set_link_up_str % device
73 check_call(cmd, shell=True)
77 class NetnsManager(object):
80 super(NetnsManager, self).__init__()
83 def config_dev(self, netdev):
84 ns, device, ip = netdev["namespace"], netdev["iface"], netdev[
85 'ip_setting'] if "ip_setting" in netdev else netdev['ip']
86 self._netns.create_namespace(ns)
87 self._netns.add_device(ns, device)
88 self._netns.config_ip(ns, device, ip)
90 ethtool.autoneg_off(device, ns)
93 def recover_dev(self, netdev):
94 ns = netdev["namespace"]
95 return self._netns.remove_namespace(ns)
97 def clean_all_namespace(self):
98 return self._netns.clean_all_namespace()
102 cmd = "ping -w2 -c1 %s" % ip
103 cmd = ns_cmd(ns, cmd)
104 child = my_popen(cmd, shell=True)
105 return 0 == child.wait()
108 if __name__ == '__main__':
109 logging.basicConfig(level=logging.DEBUG)