chore(api): use the non-deprecated nat init call
[csit.git] / resources / libraries / python / NATUtil.py
1 # Copyright (c) 2022 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 """NAT utilities library."""
15
16 from math import log2, modf
17 from pprint import pformat
18 from enum import IntEnum
19
20 from ipaddress import IPv4Address
21 from robot.api import logger
22
23 from resources.libraries.python.Constants import Constants
24 from resources.libraries.python.InterfaceUtil import InterfaceUtil
25 from resources.libraries.python.topology import Topology
26 from resources.libraries.python.PapiExecutor import PapiSocketExecutor
27
28
29 class NatConfigFlags(IntEnum):
30     """NAT plugin configuration flags"""
31     NAT_IS_NONE = 0x00
32     NAT_IS_TWICE_NAT = 0x01
33     NAT_IS_SELF_TWICE_NAT = 0x02
34     NAT_IS_OUT2IN_ONLY = 0x04
35     NAT_IS_ADDR_ONLY = 0x08
36     NAT_IS_OUTSIDE = 0x10
37     NAT_IS_INSIDE = 0x20
38     NAT_IS_STATIC = 0x40
39     NAT_IS_EXT_HOST_VALID = 0x80
40
41
42 class Nat44ConfigFlags(IntEnum):
43     """NAT44 configuration flags"""
44     NAT44_IS_ENDPOINT_INDEPENDENT = 0x00
45     NAT44_IS_ENDPOINT_DEPENDENT = 0x01
46     NAT44_IS_STATIC_MAPPING_ONLY = 0x02
47     NAT44_IS_CONNECTION_TRACKING = 0x04
48     NAT44_IS_OUT2IN_DPO = 0x08
49
50
51 class NatAddrPortAllocAlg(IntEnum):
52     """NAT Address and port assignment algorithms."""
53     NAT_ALLOC_ALG_DEFAULT = 0
54     NAT_ALLOC_ALG_MAP_E = 1
55     NAT_ALLOC_ALG_PORT_RANGE = 2
56
57
58 class NATUtil:
59     """This class defines the methods to set NAT."""
60
61     def __init__(self):
62         pass
63
64     @staticmethod
65     def enable_nat44_ed_plugin(
66         node, inside_vrf=0, outside_vrf=0, sessions=0, session_memory=0,
67         mode=u""
68     ):
69         """Enable NAT44 plugin.
70
71         :param node: DUT node.
72         :param inside_vrf: Inside VRF ID.
73         :param outside_vrf: Outside VRF ID.
74         :param sessions: Maximum number of sessions.
75         :param session_memory: Session memory size - overwrite auto calculated
76             hash allocation parameter if non-zero.
77         :param mode: NAT44 mode. Valid values:
78             - endpoint-independent
79             - endpoint-dependent
80             - static-mapping-only
81             - connection-tracking
82             - out2in-dpo
83         :type node: dict
84         :type inside_vrf: str or int
85         :type outside_vrf: str or int
86         :type sessions: str or int
87         :type session_memory: str or int
88         :type mode: str
89         """
90         cmd = u"nat44_ed_plugin_enable_disable"
91         err_msg = f"Failed to enable NAT44 plugin on the host {node[u'host']}!"
92         args_in = dict(
93             enable=True,
94             inside_vrf=int(inside_vrf),
95             outside_vrf=int(outside_vrf),
96             sessions=int(sessions),
97             session_memory=int(session_memory),
98             flags=getattr(
99                 Nat44ConfigFlags,
100                 f"NAT44_IS_{mode.replace(u'-', u'_').upper()}"
101             ).value
102         )
103
104         with PapiSocketExecutor(node) as papi_exec:
105             papi_exec.add(cmd, **args_in).get_reply(err_msg)
106
107     @staticmethod
108     def set_nat44_interface(node, interface, flag):
109         """Set inside and outside interfaces for NAT44.
110
111         :param node: DUT node.
112         :param interface: NAT44 interface.
113         :param flag: Interface NAT configuration flag name.
114         :type node: dict
115         :type interface: str
116         :type flag: str
117         """
118         cmd = u"nat44_interface_add_del_feature"
119
120         err_msg = f"Failed to set {flag} interface {interface} for NAT44 " \
121             f"on host {node[u'host']}"
122         args_in = dict(
123             sw_if_index=InterfaceUtil.get_sw_if_index(node, interface),
124             is_add=1,
125             flags=getattr(NatConfigFlags, flag).value
126         )
127
128         with PapiSocketExecutor(node) as papi_exec:
129             papi_exec.add(cmd, **args_in).get_reply(err_msg)
130
131     @staticmethod
132     def set_nat44_interfaces(node, int_in, int_out):
133         """Set inside and outside interfaces for NAT44.
134
135         :param node: DUT node.
136         :param int_in: Inside interface.
137         :param int_out: Outside interface.
138         :type node: dict
139         :type int_in: str
140         :type int_out: str
141         """
142         NATUtil.set_nat44_interface(node, int_in, u"NAT_IS_INSIDE")
143         NATUtil.set_nat44_interface(node, int_out, u"NAT_IS_OUTSIDE")
144
145     @staticmethod
146     def set_nat44_address_range(
147             node, start_ip, end_ip, vrf_id=Constants.BITWISE_NON_ZERO,
148             flag=u"NAT_IS_NONE"):
149         """Set NAT44 address range.
150
151         The return value is a callable (zero argument Python function)
152         which can be used to reset NAT state, so repeated trial measurements
153         hit the same slow path.
154
155         :param node: DUT node.
156         :param start_ip: IP range start.
157         :param end_ip: IP range end.
158         :param vrf_id: VRF index (Optional).
159         :param flag: NAT flag name.
160         :type node: dict
161         :type start_ip: str
162         :type end_ip: str
163         :type vrf_id: int
164         :type flag: str
165         :returns: Resetter of the NAT state.
166         :rtype: Callable[[], None]
167         """
168         cmd = u"nat44_add_del_address_range"
169         err_msg = f"Failed to set NAT44 address range on host {node[u'host']}"
170         args_in = dict(
171             is_add=True,
172             first_ip_address=IPv4Address(str(start_ip)).packed,
173             last_ip_address=IPv4Address(str(end_ip)).packed,
174             vrf_id=vrf_id,
175             flags=getattr(NatConfigFlags, flag).value
176         )
177
178         with PapiSocketExecutor(node) as papi_exec:
179             papi_exec.add(cmd, **args_in).get_reply(err_msg)
180
181         # A closure, accessing the variables above.
182         def resetter():
183             """Delete and re-add the NAT range setting."""
184             with PapiSocketExecutor(node) as papi_exec:
185                 args_in[u"is_add"] = False
186                 papi_exec.add(cmd, **args_in)
187                 args_in[u"is_add"] = True
188                 papi_exec.add(cmd, **args_in)
189                 papi_exec.get_replies(err_msg)
190
191         return resetter
192
193     @staticmethod
194     def show_nat44_config(node):
195         """Show the NAT44 plugin running configuration.
196
197         :param node: DUT node.
198         :type node: dict
199         """
200         cmd = u"nat44_show_running_config"
201         err_msg = f"Failed to get NAT44 configuration on host {node[u'host']}"
202
203         with PapiSocketExecutor(node) as papi_exec:
204             reply = papi_exec.add(cmd).get_reply(err_msg)
205
206         logger.debug(f"NAT44 Configuration:\n{pformat(reply)}")
207
208     @staticmethod
209     def show_nat44_summary(node):
210         """Show NAT44 summary on the specified topology node.
211
212         :param node: Topology node.
213         :type node: dict
214         :returns: NAT44 summary data.
215         :rtype: str
216         """
217         return PapiSocketExecutor.run_cli_cmd(node, u"show nat44 summary")
218
219     @staticmethod
220     def show_nat_base_data(node):
221         """Show the NAT base data.
222
223         Used data sources:
224
225             nat_worker_dump
226             nat44_interface_addr_dump
227             nat44_address_dump
228             nat44_static_mapping_dump
229             nat44_interface_dump
230
231         :param node: DUT node.
232         :type node: dict
233         """
234         cmds = [
235             u"nat_worker_dump",
236             u"nat44_interface_addr_dump",
237             u"nat44_address_dump",
238             u"nat44_static_mapping_dump",
239             u"nat44_interface_dump",
240         ]
241         PapiSocketExecutor.dump_and_log(node, cmds)
242
243     @staticmethod
244     def show_nat_user_data(node):
245         """Show the NAT user data.
246
247         Used data sources:
248
249             nat44_user_dump
250             nat44_user_session_dump
251
252         :param node: DUT node.
253         :type node: dict
254         """
255         cmds = [
256             u"nat44_user_dump",
257             u"nat44_user_session_dump",
258         ]
259         PapiSocketExecutor.dump_and_log(node, cmds)
260
261     @staticmethod
262     def compute_max_translations_per_thread(sessions, threads):
263         """Compute value of max_translations_per_thread NAT44 parameter based on
264         total number of worker threads.
265
266         :param sessions: Required number of NAT44 sessions.
267         :param threads: Number of worker threads.
268         :type sessions: int
269         :type threads: int
270         :returns: Value of max_translations_per_thread NAT44 parameter.
271         :rtype: int
272         """
273         # vpp-device tests have not dedicated physical core so
274         # ${dp_count_int} == 0 but we need to use one thread
275         threads = 1 if not int(threads) else int(threads)
276         rest, mult = modf(log2(sessions/(10*threads)))
277         return 2 ** (int(mult) + (1 if rest else 0)) * 10
278
279     @staticmethod
280     def get_nat44_sessions_number(node, proto):
281         """Get number of established NAT44 sessions from NAT44 mapping data.
282
283         This keyword uses output from a CLI command,
284         so it can start failing when VPP changes the output format.
285         TODO: Switch to API (or stat segment) when available.
286
287         The current implementation supports both 2202 and post-2202 format.
288         (The Gerrit number changing the output format is 34877.)
289
290         For TCP proto, the post-2202 format includes "timed out"
291         established sessions into its count of total sessions.
292         As the tests should fail if a session is timed-out,
293         the logic substracts timed out sessions for the resturned value.
294
295         The 2202 output reports most of TCP sessions as in "transitory" state,
296         as opposed to "established", but the previous CSIT logic tolerated that.
297         Ideally, whis keyword would add establised and transitory sessions
298         (but without CLOSED and WAIT_CLOSED sessions) and return that.
299         The current implementation simply returns "total tcp sessions" value,
300         to preserve the previous CSIT behavior for 2202 output.
301
302         :param node: DUT node.
303         :param proto: Required protocol - TCP/UDP/ICMP.
304         :type node: dict
305         :type proto: str
306         :returns: Number of active established NAT44 sessions.
307         :rtype: int
308         :raises ValueError: If not supported protocol.
309         :raises RuntimeError: If output is not formatted as expected.
310         """
311         proto_l = proto.strip().lower()
312         if proto_l not in [u"udp", u"tcp", u"icmp"]:
313             raise ValueError(f"Unsupported protocol: {proto}!")
314         summary_text = NATUtil.show_nat44_summary(node)
315         summary_lines = summary_text.splitlines()
316         # Output from VPP v22.02 and before, delete when no longer needed.
317         pattern_2202 = f"total {proto_l} sessions:"
318         if pattern_2202 in summary_text:
319             for line in summary_lines:
320                 if pattern_2202 not in line:
321                     continue
322                 return int(line.split(u":", 1)[1].strip())
323         # Post-2202, the proto info and session info are not on the same line.
324         found = False
325         for line in summary_lines:
326             if not found:
327                 if f"{proto_l} sessions:" in line:
328                     found = True
329                 continue
330             # Proto is found, find the line we are interested in.
331             if proto_l == u"tcp" and u"established" not in line:
332                 continue
333             if u"total" not in line and u"established" not in line:
334                 raise RuntimeError(f"show nat summary: no {proto} total.")
335             # We have the line with relevant numbers.
336             total_part, timed_out_part = line.split(u"(", 1)
337             timed_out_part = timed_out_part.split(u")", 1)[0]
338             total_count = int(total_part.split(u":", 1)[1].strip())
339             timed_out_count = int(timed_out_part.split(u":", 1)[1].strip())
340             active_count = total_count - timed_out_count
341             return active_count
342         raise RuntimeError(u"Unknown format of show nat44 summary")
343
344     # DET44 PAPI calls
345     # DET44 means deterministic mode of NAT44
346     @staticmethod
347     def enable_det44_plugin(node, inside_vrf=0, outside_vrf=0):
348         """Enable DET44 plugin.
349
350         :param node: DUT node.
351         :param inside_vrf: Inside VRF ID.
352         :param outside_vrf: Outside VRF ID.
353         :type node: dict
354         :type inside_vrf: str or int
355         :type outside_vrf: str or int
356         """
357         cmd = u"det44_plugin_enable_disable"
358         err_msg = f"Failed to enable DET44 plugin on the host {node[u'host']}!"
359         args_in = dict(
360             enable=True,
361             inside_vrf=int(inside_vrf),
362             outside_vrf=int(outside_vrf)
363         )
364
365         with PapiSocketExecutor(node) as papi_exec:
366             papi_exec.add(cmd, **args_in).get_reply(err_msg)
367
368     @staticmethod
369     def set_det44_interface(node, if_key, is_inside):
370         """Enable DET44 feature on the interface.
371
372         :param node: DUT node.
373         :param if_key: Interface key from topology file of interface
374             to enable DET44 feature on.
375         :param is_inside: True if interface is inside, False if outside.
376         :type node: dict
377         :type if_key: str
378         :type is_inside: bool
379         """
380         cmd = u"det44_interface_add_del_feature"
381         err_msg = f"Failed to enable DET44 feature on the interface {if_key} " \
382             f"on the host {node[u'host']}!"
383         args_in = dict(
384             is_add=True,
385             is_inside=is_inside,
386             sw_if_index=Topology.get_interface_sw_index(node, if_key)
387         )
388
389         with PapiSocketExecutor(node) as papi_exec:
390             papi_exec.add(cmd, **args_in).get_reply(err_msg)
391
392     @staticmethod
393     def set_det44_mapping(node, ip_in, subnet_in, ip_out, subnet_out):
394         """Set DET44 mapping.
395
396         The return value is a callable (zero argument Python function)
397         which can be used to reset NAT state, so repeated trial measurements
398         hit the same slow path.
399
400         :param node: DUT node.
401         :param ip_in: Inside IP.
402         :param subnet_in: Inside IP subnet.
403         :param ip_out: Outside IP.
404         :param subnet_out: Outside IP subnet.
405         :type node: dict
406         :type ip_in: str
407         :type subnet_in: str or int
408         :type ip_out: str
409         :type subnet_out: str or int
410         """
411         cmd = u"det44_add_del_map"
412         err_msg = f"Failed to set DET44 mapping on the host {node[u'host']}!"
413         args_in = dict(
414             is_add=True,
415             in_addr=IPv4Address(str(ip_in)).packed,
416             in_plen=int(subnet_in),
417             out_addr=IPv4Address(str(ip_out)).packed,
418             out_plen=int(subnet_out)
419         )
420
421         with PapiSocketExecutor(node) as papi_exec:
422             papi_exec.add(cmd, **args_in).get_reply(err_msg)
423
424         # A closure, accessing the variables above.
425         def resetter():
426             """Delete and re-add the deterministic NAT mapping."""
427             with PapiSocketExecutor(node) as papi_exec:
428                 args_in[u"is_add"] = False
429                 papi_exec.add(cmd, **args_in)
430                 args_in[u"is_add"] = True
431                 papi_exec.add(cmd, **args_in)
432                 papi_exec.get_replies(err_msg)
433
434         return resetter
435
436     @staticmethod
437     def get_det44_mapping(node):
438         """Get DET44 mapping data.
439
440         :param node: DUT node.
441         :type node: dict
442         :returns: Dictionary of DET44 mapping data.
443         :rtype: dict
444         """
445         cmd = u"det44_map_dump"
446         err_msg = f"Failed to get DET44 mapping data on the host " \
447             f"{node[u'host']}!"
448         args_in = dict()
449         with PapiSocketExecutor(node) as papi_exec:
450             details = papi_exec.add(cmd, **args_in).get_reply(err_msg)
451
452         return details
453
454     @staticmethod
455     def get_det44_sessions_number(node):
456         """Get number of established DET44 sessions from actual DET44 mapping
457         data.
458         :param node: DUT node.
459         :type node: dict
460         :returns: Number of established DET44 sessions.
461         :rtype: int
462         """
463         det44_data = NATUtil.get_det44_mapping(node)
464         return det44_data.get(u"ses_num", 0)
465
466     @staticmethod
467     def show_det44(node):
468         """Show DET44 data.
469
470         Used data sources:
471
472             det44_interface_dump
473             det44_map_dump
474             det44_session_dump
475
476         :param node: DUT node.
477         :type node: dict
478         """
479         cmds = [
480             u"det44_interface_dump",
481             u"det44_map_dump",
482             u"det44_session_dump",
483         ]
484         PapiSocketExecutor.dump_and_log(node, cmds)