Refactor IPv4 utils
[csit.git] / resources / libraries / python / InterfaceUtil.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Interface util library"""
15
16 from resources.libraries.python.ssh import exec_cmd_no_error
17 from resources.libraries.python.topology import NodeType, Topology
18 from resources.libraries.python.VatExecutor import VatExecutor
19
20
21 class InterfaceUtil(object):
22     """General utilities for managing interfaces"""
23
24     @staticmethod
25     def set_interface_state(node, interface, state):
26         """Set interface state on a node.
27
28         Function can be used for DUTs as well as for TGs.
29
30         :param node: node where the interface is
31         :param interface: interface name
32         :param state: one of 'up' or 'down'
33         :type node: dict
34         :type interface: str
35         :type state: str
36         :return: nothing
37         """
38         if node['type'] == NodeType.DUT:
39             if state == 'up':
40                 state = 'admin-up link-up'
41             elif state == 'down':
42                 state = 'admin-down link-down'
43             else:
44                 raise Exception('Unexpected interface state: {}'.format(state))
45
46             sw_if_index = Topology.get_interface_sw_index(node, interface)
47             VatExecutor.cmd_from_template(node, 'set_if_state.vat',
48                                           sw_if_index=sw_if_index, state=state)
49
50         elif node['type'] == NodeType.TG:
51             cmd = 'ip link set {} {}'.format(interface, state)
52             exec_cmd_no_error(node, cmd, sudo=True)
53         else:
54             raise Exception('Unknown NodeType: "{}"'.format(node['type']))