7 from vstf.common.utils import IPCommandHelper
8 from vstf.agent.perf import ethtool
9 from vstf.common.utils import check_call, check_output, ns_cmd, my_popen, my_sleep
11 LOG = logging.getLogger(__name__)
16 super(Netns, self).__init__()
17 self.netns_add_str = "ip netns add %s"
18 self.netns_del_str = " ip netns del %s"
19 self.netns_add_device_str = " ip link set %s netns %s"
20 self.set_link_up_str = "ip link set dev %s up"
21 self.set_link_addr_str = "ip addr replace %s dev %s"
22 self.netns_remove_device_str = "ip netns exec %s ip link set %s netns 1"
23 # self.set_link_addr_str = "ifconfig %s %s up"
26 def clean_all_namespace(self):
27 out = check_output("ip netns list", shell=True)
28 for ns in out.splitlines():
29 self.remove_namespace(ns)
32 def create_namespace(self, name):
33 if name in (None, 'None', 'none'):
35 cmd = self.netns_add_str % name
36 check_call(cmd, shell=True)
39 def remove_namespace(self, ns):
40 if ns in (None, 'None', 'none'):
42 ip_helper = IPCommandHelper(ns)
43 for dev in ip_helper.device_mac_map:
44 cmd = self.netns_remove_device_str % (ns, dev)
45 check_call(cmd, shell=True)
46 self.activate_device(None, dev)
47 cmd = self.netns_del_str % ns
48 check_call(cmd, shell=True)
51 def add_device(self, ns, device):
54 cmd = self.netns_add_device_str % (device, ns)
55 check_call(cmd, shell=True)
58 def config_ip(self, ns, device, ip):
59 self.activate_device(ns, device)
60 cmd = self.set_link_addr_str % (ip, device)
62 check_call(cmd, shell=True)
65 def activate_device(self, ns, device):
66 cmd = self.set_link_up_str % device
68 check_call(cmd, shell=True)
72 class NetnsManager(object):
74 super(NetnsManager, self).__init__()
77 def config_dev(self, netdev):
78 ns, device, ip = netdev["namespace"], netdev["iface"], netdev['ip_setting'] if "ip_setting" in netdev else \
80 self._netns.create_namespace(ns)
81 self._netns.add_device(ns, device)
82 self._netns.config_ip(ns, device, ip)
84 ethtool.autoneg_off(device, ns)
87 def recover_dev(self, netdev):
88 ns = netdev["namespace"]
89 return self._netns.remove_namespace(ns)
91 def clean_all_namespace(self):
92 return self._netns.clean_all_namespace()
96 cmd = "ping -w2 -c1 %s" % ip
98 child = my_popen(cmd, shell=True)
99 return 0 == child.wait()
102 if __name__ == '__main__':
103 logging.basicConfig(level=logging.DEBUG)