Update VPP_STABLE_VER files
[csit.git] / resources / libraries / python / Iperf3.py
1 # Copyright (c) 2023 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 """iPerf3 utilities library."""
15
16 import json
17
18 from resources.libraries.python.Constants import Constants
19 from resources.libraries.python.CpuUtils import CpuUtils
20 from resources.libraries.python.IPUtil import IPUtil
21 from resources.libraries.python.Namespaces import Namespaces
22 from resources.libraries.python.OptionString import OptionString
23 from resources.libraries.python.ssh import exec_cmd, exec_cmd_no_error
24
25
26 class Iperf3:
27     """iPerf3 traffic generator utilities."""
28
29     def __init__(self):
30         """Initialize iPerf3 class."""
31         # Computed affinity for iPerf server.
32         self._s_affinity = None
33         # Computed affinity for iPerf client.
34         self._c_affinity = None
35
36     @staticmethod
37     def get_iperf_type():
38         """Log and return the installed traffic generator type.
39
40         :returns: Traffic generator type string.
41         :rtype: str
42         """
43         return "IPERF"
44
45     @staticmethod
46     def get_iperf_version(node):
47         """Log and return the installed traffic generator version.
48
49         :param node: Node from topology file.
50         :type node: dict
51         :returns: Traffic generator version string.
52         :rtype: str
53         """
54         command = f"iperf3 --version | head -1"
55         message = u"Get iPerf version failed!"
56         stdout, _ = exec_cmd_no_error(node, command, message=message)
57         return stdout.strip()
58
59     def initialize_iperf_server(
60             self, node, pf_key, interface, bind, bind_gw, bind_mask,
61             namespace=None, cpu_skip_cnt=0, cpu_cnt=1, instances=1):
62         """iPerf3 initialization.
63
64         :param node: Topology node running iPerf3 server.
65         :param pf_key: First TG's interface (To compute numa location).
66         :param interface: Name of TG bind interface.
67         :param bind: Bind to host, one of node's addresses.
68         :param bind_gw: Bind gateway (required for default route).
69         :param bind_mask: Bind address mask.
70         :param namespace: Name of TG namespace to execute.
71         :param cpu_skip_cnt: Amount of CPU cores to skip.
72         :param cpu_cnt: iPerf3 main thread count.
73         :param instances: Number of simultaneous iPerf3 instances.
74         :type node: dict
75         :type pf_key: str
76         :type interface: str
77         :type bind: str
78         :type bind_gw: str
79         :type bind_mask: str
80         :type namespace: str
81         :type cpu_skip_cnt: int
82         :type cpu_cnt: int
83         :type instances: int
84         """
85         if Iperf3.is_iperf_running(node):
86             Iperf3.teardown_iperf(node)
87
88         if namespace:
89             IPUtil.set_linux_interface_ip(
90                 node, interface=interface, ip_addr=bind, prefix=bind_mask,
91                 namespace=namespace)
92             IPUtil.set_linux_interface_up(
93                 node, interface=interface, namespace=namespace)
94             Namespaces.add_default_route_to_namespace(
95                 node, namespace=namespace, default_route=bind_gw)
96
97         # Compute affinity for iPerf server.
98         self._s_affinity = CpuUtils.get_affinity_iperf(
99             node, pf_key, cpu_skip_cnt=cpu_skip_cnt,
100             cpu_cnt=cpu_cnt * instances)
101         # Compute affinity for iPerf client.
102         self._c_affinity = CpuUtils.get_affinity_iperf(
103             node, pf_key, cpu_skip_cnt=cpu_skip_cnt + cpu_cnt * instances,
104             cpu_cnt=cpu_cnt * instances)
105
106         for i in range(0, instances):
107             Iperf3.start_iperf_server(
108                 node, namespace=namespace, port=5201 + i,
109                 affinity=self._s_affinity)
110
111     @staticmethod
112     def start_iperf_server(
113             node, namespace=None, port=5201, affinity=None):
114         """Start iPerf3 server instance as a deamon.
115
116         :param node: Topology node running iPerf3 server.
117         :param namespace: Name of TG namespace to execute.
118         :param port: The server port for the server to listen on.
119         :param affinity: iPerf3 server affinity.
120         :type node: dict
121         :type namespace: str
122         :type port: int
123         :type affinity: str
124         """
125         cmd = IPerf3Server.iperf3_cmdline(
126             namespace=namespace, port=port, affinity=affinity)
127         exec_cmd_no_error(
128             node, cmd, sudo=True, message=u"Failed to start iPerf3 server!")
129
130     @staticmethod
131     def is_iperf_running(node):
132         """Check if iPerf3 is running using pgrep.
133
134         :param node: Topology node running iPerf3.
135         :type node: dict
136         :returns: True if iPerf3 is running otherwise False.
137         :rtype: bool
138         """
139         ret, _, _ = exec_cmd(node, u"pgrep iperf3", sudo=True)
140         return bool(int(ret) == 0)
141
142     @staticmethod
143     def teardown_iperf(node):
144         """iPerf3 teardown.
145
146         :param node: Topology node running iPerf3.
147         :type node: dict
148         """
149         pidfile = u"/tmp/iperf3_server.pid"
150         logfile = u"/tmp/iperf3.log"
151
152         exec_cmd_no_error(
153             node,
154             f"sh -c 'if [ -f {pidfile} ]; then "
155             f"pkill iperf3; "
156             f"cat {logfile}; "
157             f"rm {logfile}; "
158             f"fi'",
159             sudo=True, message=u"iPerf3 kill failed!")
160
161     def iperf_client_start_remote_exec(
162             self, node, duration, rate, frame_size, async_call=False,
163             warmup_time=0, traffic_directions=1, namespace=None, udp=False,
164             host=None, bind=None, affinity=None):
165         """Execute iPerf3 client script on remote node over ssh to start running
166         traffic.
167
168         :param node: Topology node running iPerf3.
169         :param duration: Time expressed in seconds for how long to send traffic.
170         :param rate: Traffic rate.
171         :param frame_size: L2 frame size to send (without padding and IPG).
172         :param async_call: If enabled then don't wait for all incoming traffic.
173         :param warmup_time: Warmup time period.
174         :param traffic_directions: Traffic is bi- (2) or uni- (1) directional.
175             Default: 1
176         :param namespace: Namespace to execute iPerf3 client on.
177         :param udp: UDP traffic.
178         :param host: Client connecting to an iPerf server running on host.
179         :param bind: Client bind IP address.
180         :param affinity: iPerf3 client affinity.
181         :type node: dict
182         :type duration: float
183         :type rate: str
184         :type frame_size: str
185         :type async_call: bool
186         :type warmup_time: float
187         :type traffic_directions: int
188         :type namespace: str
189         :type udp: bool
190         :type host: str
191         :type bind: str
192         :type affinity: str
193         :returns: List of iPerf3 PIDs.
194         :rtype: list
195         """
196         if not isinstance(duration, (float, int)):
197             duration = float(duration)
198         if not isinstance(warmup_time, (float, int)):
199             warmup_time = float(warmup_time)
200         if not affinity:
201             affinity = self._c_affinity
202
203         kwargs = dict()
204         if namespace:
205             kwargs[u"namespace"] = namespace
206         kwargs[u"host"] = host
207         kwargs[u"bind"] = bind
208         kwargs[u"udp"] = udp
209         if affinity:
210             kwargs[u"affinity"] = affinity
211         kwargs[u"duration"] = duration
212         kwargs[u"rate"] = rate
213         kwargs[u"frame_size"] = frame_size
214         kwargs[u"warmup_time"] = warmup_time
215         kwargs[u"traffic_directions"] = traffic_directions
216         kwargs[u"async_call"] = async_call
217
218         cmd = IPerf3Client.iperf3_cmdline(**kwargs)
219
220         stdout, _ = exec_cmd_no_error(
221             node, cmd, timeout=int(duration) + 30,
222             message=u"iPerf3 runtime error!")
223
224         if async_call:
225             return stdout.split()
226         return json.loads(stdout)
227
228     @staticmethod
229     def iperf_client_stop_remote_exec(node, pids):
230         """Stop iPerf3 client execution.
231
232         :param pids: PID or List of PIDs of iPerf3 client.
233         :type pids: str or list
234         """
235         if not isinstance(pids, list):
236             pids = [pids]
237
238         for pid in pids:
239             exec_cmd_no_error(
240                 node, f"kill {pid}", sudo=True, message=u"Kill iPerf3 failed!")
241
242
243 class IPerf3Server:
244     """iPerf3 server utilities."""
245
246     @staticmethod
247     def iperf3_cmdline(**kwargs):
248         """Get iPerf3 server command line.
249
250         :param kwargs: List of iPerf3 server parameters.
251         :type kwargs: dict
252         :returns: iPerf3 server command line.
253         :rtype: OptionString
254         """
255         cmd = OptionString()
256         if kwargs['namespace']:
257             cmd.add(f"ip netns exec {kwargs['namespace']}")
258         cmd.add(f"iperf3")
259
260         cmd_options = OptionString(prefix=u"--")
261         # Run iPerf in server mode. (This will only allow one iperf connection
262         # at a time)
263         cmd_options.add(
264             u"server")
265
266         # Run the server in background as a daemon.
267         cmd_options.add_if_from_dict(
268             u"daemon", u"daemon", kwargs, True)
269
270         # Write a file with the process ID, most useful when running as a
271         # daemon.
272         cmd_options.add_with_value_from_dict(
273             u"pidfile", u"pidfile", kwargs, f"/tmp/iperf3_server.pid")
274
275         # Send output to a log file.
276         cmd_options.add_with_value_from_dict(
277             u"logfile", u"logfile", kwargs, f"/tmp/iperf3.log")
278
279         # The server port for the server to listen on and the client to
280         # connect to. This should be the same in both client and server.
281         # Default is 5201.
282         cmd_options.add_with_value_from_dict(
283             u"port", u"port", kwargs, 5201)
284
285         # Set the CPU affinity, if possible (Linux and FreeBSD only).
286         cmd_options.add_with_value_from_dict(
287             u"affinity", u"affinity", kwargs)
288
289         # Output in JSON format.
290         cmd_options.add_if_from_dict(
291             u"json", u"json", kwargs, True)
292
293         # Give more detailed output.
294         cmd_options.add_if_from_dict(
295             u"verbose", u"verbose", kwargs, True)
296
297         return cmd.extend(cmd_options)
298
299
300 class IPerf3Client:
301     """iPerf3 client utilities."""
302
303     @staticmethod
304     def iperf3_cmdline(**kwargs):
305         """Get iperf_client driver command line.
306
307         :param kwargs: List of iperf_client driver parameters.
308         :type kwargs: dict
309         :returns: iperf_client driver command line.
310         :rtype: OptionString
311         """
312         cmd = OptionString()
313         cmd.add(u"python3")
314         dirname = f"{Constants.REMOTE_FW_DIR}/resources/tools/iperf"
315         cmd.add(f"'{dirname}/iperf_client.py'")
316
317         cmd_options = OptionString(prefix=u"--")
318         # Namespace to execute iPerf3 client on.
319         cmd_options.add_with_value_from_dict(
320             u"namespace", u"namespace", kwargs)
321
322         # Client connecting to an iPerf3 server running on host.
323         cmd_options.add_with_value_from_dict(
324             u"host", u"host", kwargs)
325
326         # Client bind IP address.
327         cmd_options.add_with_value_from_dict(
328             u"bind", u"bind", kwargs)
329
330         # Use UDP rather than TCP.
331         cmd_options.add_if_from_dict(
332             u"udp", u"udp", kwargs, False)
333
334         # Set the CPU affinity, if possible.
335         cmd_options.add_with_value_from_dict(
336             u"affinity", u"affinity", kwargs)
337
338         # Time expressed in seconds for how long to send traffic.
339         cmd_options.add_with_value_from_dict(
340             u"duration", u"duration", kwargs)
341
342         # Send bi- (2) or uni- (1) directional traffic.
343         cmd_options.add_with_value_from_dict(
344             u"traffic_directions", u"traffic_directions", kwargs, 1)
345
346         # Traffic warm-up time in seconds, (0=disable).
347         cmd_options.add_with_value_from_dict(
348             u"warmup_time", u"warmup_time", kwargs, 5.0)
349
350         # L2 frame size to send (without padding and IPG).
351         cmd_options.add_with_value_from_dict(
352             u"frame_size", u"frame_size", kwargs)
353
354         # Traffic rate expressed with units.
355         cmd_options.add_with_value_from_dict(
356             u"rate", u"rate", kwargs)
357
358         # If enabled then don't wait for all incoming traffic.
359         cmd_options.add_if_from_dict(
360             u"async_start", u"async_call", kwargs, False)
361
362         # Number of iPerf3 client parallel instances.
363         cmd_options.add_with_value_from_dict(
364             u"instances", u"instances", kwargs, 1)
365
366         # Number of iPerf3 client parallel flows.
367         cmd_options.add_with_value_from_dict(
368             u"parallel", u"parallel", kwargs, 8)
369
370         return cmd.extend(cmd_options)