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