FIX: Memif tests failing
[csit.git] / resources / libraries / python / Memif.py
1 # Copyright (c) 2017 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 """Memif interface library."""
15
16 from resources.libraries.python.ssh import SSH
17 from resources.libraries.python.VatExecutor import VatExecutor, VatTerminal
18 from resources.libraries.python.topology import Topology
19
20
21 class Memif(object):
22     """Memif interface class."""
23
24     def __init__(self):
25         pass
26
27     @staticmethod
28     def create_memif_interface(node, filename, mid, sid, role='master'):
29         """Create Memif interface on the given node.
30
31         :param node: Given node to create Memif interface on.
32         :param filename: Memif interface socket filename.
33         :param mid: Memif interface ID.
34         :param sid: Socket ID.
35         :param role: Memif interface role [master|slave]. Default is master.
36         :type node: dict
37         :type filename: str
38         :type mid: str
39         :type sid: str
40         :type role: str
41         :returns: SW interface index.
42         :rtype: int
43         :raises ValueError: If command 'create memif' fails.
44         """
45
46         with VatTerminal(node, json_param=False) as vat:
47             vat.vat_terminal_exec_cmd_from_template(
48                 'memif_socket_filename_add_del.vat',
49                 add_del='add', id=sid, filename='/tmp/'+filename)
50             vat.vat_terminal_exec_cmd_from_template(
51                 'memif_create.vat', id=mid, socket=sid, role=role)
52             if 'sw_if_index' in vat.vat_stdout:
53                 try:
54                     sw_if_idx = int(vat.vat_stdout.split()[4])
55                     if_key = Topology.add_new_port(node, 'memif')
56                     Topology.update_interface_sw_if_index(
57                         node, if_key, sw_if_idx)
58                     ifc_name = Memif.vpp_get_memif_interface_name(
59                         node, sw_if_idx)
60                     Topology.update_interface_name(node, if_key, ifc_name)
61                     ifc_mac = Memif.vpp_get_memif_interface_mac(node, sw_if_idx)
62                     Topology.update_interface_mac_address(node, if_key, ifc_mac)
63                     Topology.update_interface_memif_socket(node, if_key,
64                                                            '/tmp/'+filename)
65                     Topology.update_interface_memif_id(node, if_key, mid)
66                     Topology.update_interface_memif_role(node, if_key, role)
67                     return sw_if_idx
68                 except KeyError:
69                     raise ValueError('Create Memif interface failed on node '
70                                      '{}'.format(node['host']))
71             else:
72                 raise ValueError('Create Memif interface failed on node '
73                                  '{}'.format(node['host']))
74
75     @staticmethod
76     def dump_memif(node):
77         """Dump Memif data for the given node.
78
79         :param node: Given node to show Memif data on.
80         :type node: dict
81         """
82         vat = VatExecutor()
83         vat.execute_script("memif_dump.vat", node, json_out=False)
84
85     @staticmethod
86     def show_memif(node):
87         """Show Memif data for the given node.
88
89         :param node: Given node to show Memif data on.
90         :type node: dict
91         """
92         vat = VatExecutor()
93         vat.execute_script("show_memif.vat", node, json_out=False)
94
95     @staticmethod
96     def clear_memif_socks(node, *socks):
97         """Clear Memif sockets for the given node.
98
99         :param node: Given node to clear Memif sockets on.
100         :param socks: Memif sockets.
101         :type node: dict
102         :type socks: list
103         """
104         ssh = SSH()
105         ssh.connect(node)
106
107         for sock in socks:
108             ssh.exec_command_sudo('rm -f {}'.format(sock))
109
110     @staticmethod
111     def parse_memif_dump_data(memif_data):
112         """Convert Memif data to dictionary.
113
114         :param memif_data: Dump of Memif interfaces data.
115         :type memif_data: str
116         :returns: Memif interfaces data in dictionary.
117         :rtype: dict
118         :raises RuntimeError: If there is no memif interface name found in
119             provided data.
120         """
121         memif_name = None
122         memif_dict = dict()
123         memif_data = str(memif_data)
124         values = dict()
125
126         clutter = ['vat#']
127         for garbage in clutter:
128             memif_data = memif_data.replace(garbage, '')
129
130         for line in memif_data.splitlines():
131             if line.startswith('Sending') or len(line) == 0:
132                 continue
133             elif line.startswith('memif'):
134                 if memif_name:
135                     memif_dict[memif_name] = values
136                 line_split = line.split(':', 1)
137                 memif_name = str(line_split[0])
138                 values = dict()
139                 line = line_split[1]
140             line_split = line.split()
141             for i in range(0, len(line_split), 2):
142                 key = str(line_split[i])
143                 try:
144                     value = line_split[i+1]
145                 except IndexError:
146                     value = None
147                 values[key] = value
148         if memif_name:
149             memif_dict[memif_name] = values
150         else:
151             raise RuntimeError('No memif interface name found')
152
153         return memif_dict
154
155     @staticmethod
156     def vpp_get_memif_interface_name(node, sw_if_idx):
157         """Get Memif interface name from Memif interfaces dump.
158
159         :param node: DUT node.
160         :param sw_if_idx: DUT node.
161         :type node: dict
162         :type sw_if_idx: int
163         :returns: Memif interface name.
164         :rtype: str
165         """
166         with VatTerminal(node, json_param=False) as vat:
167             vat.vat_terminal_exec_cmd_from_template('memif_dump.vat')
168             memif_data = Memif.parse_memif_dump_data(vat.vat_stdout)
169             for item in memif_data:
170                 if memif_data[item]['sw_if_index'] == str(sw_if_idx):
171                     return item
172                 return None
173
174     @staticmethod
175     def vpp_get_memif_interface_mac(node, sw_if_idx):
176         """Get Memif interface MAC address from Memif interfaces dump.
177
178         :param node: DUT node.
179         :param sw_if_idx: DUT node.
180         :type node: dict
181         :type sw_if_idx: int
182         :returns: Memif interface MAC address.
183         :rtype: str
184         """
185         with VatTerminal(node, json_param=False) as vat:
186             vat.vat_terminal_exec_cmd_from_template('memif_dump.vat')
187             memif_data = Memif.parse_memif_dump_data(vat.vat_stdout)
188             for item in memif_data:
189                 if memif_data[item]['sw_if_index'] == str(sw_if_idx):
190                     return memif_data[item].get('mac', None)
191
192     @staticmethod
193     def vpp_get_memif_interface_socket(node, sw_if_idx):
194         """Get Memif interface socket path from Memif interfaces dump.
195
196         :param node: DUT node.
197         :param sw_if_idx: DUT node.
198         :type node: dict
199         :type sw_if_idx: int
200         :returns: Memif interface socket path.
201         :rtype: str
202         """
203         with VatTerminal(node, json_param=False) as vat:
204             vat.vat_terminal_exec_cmd_from_template('memif_dump.vat')
205             memif_data = Memif.parse_memif_dump_data(vat.vat_stdout)
206             for item in memif_data:
207                 if memif_data[item]['sw_if_index'] == str(sw_if_idx):
208                     return memif_data[item].get('socket', None)
209
210     @staticmethod
211     def vpp_get_memif_interface_id(node, sw_if_idx):
212         """Get Memif interface ID from Memif interfaces dump.
213
214         :param node: DUT node.
215         :param sw_if_idx: DUT node.
216         :type node: dict
217         :type sw_if_idx: int
218         :returns: Memif interface ID.
219         :rtype: int
220         """
221         with VatTerminal(node, json_param=False) as vat:
222             vat.vat_terminal_exec_cmd_from_template('memif_dump.vat')
223             memif_data = Memif.parse_memif_dump_data(vat.vat_stdout)
224             for item in memif_data:
225                 if memif_data[item]['sw_if_index'] == str(sw_if_idx):
226                     return int(memif_data[item].get('id', None))
227
228     @staticmethod
229     def vpp_get_memif_interface_role(node, sw_if_idx):
230         """Get Memif interface role from Memif interfaces dump.
231
232         :param node: DUT node.
233         :param sw_if_idx: DUT node.
234         :type node: dict
235         :type sw_if_idx: int
236         :returns: Memif interface role.
237         :rtype: int
238         """
239         with VatTerminal(node, json_param=False) as vat:
240             vat.vat_terminal_exec_cmd_from_template('memif_dump.vat')
241             memif_data = Memif.parse_memif_dump_data(vat.vat_stdout)
242             for item in memif_data:
243                 if memif_data[item]['sw_if_index'] == str(sw_if_idx):
244                     return memif_data[item].get('role', None)