b1d0c9e993b69e9d271d41b7975d1c4b3d641c5a
[csit.git] / resources / libraries / python / autogen / Regenerator.py
1 # Copyright (c) 2019 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 """Module defining utilities for test directory regeneration."""
15
16 import sys
17
18 from glob import glob
19 from io import open
20 from os import getcwd
21
22
23 from resources.libraries.python.Constants import Constants
24 from resources.libraries.python.autogen.Testcase import Testcase
25
26
27 PROTOCOL_TO_MIN_FRAME_SIZE = {
28     u"ip4": 64,
29     u"ip6": 78,
30     u"ethip4vxlan": 114,  # What is the real minimum for latency stream?
31     u"dot1qip4vxlan": 118
32 }
33 MIN_FRAME_SIZE_VALUES = list(PROTOCOL_TO_MIN_FRAME_SIZE.values())
34
35
36 def replace_defensively(
37         whole, to_replace, replace_with, how_many, msg, in_filename):
38     """Replace substrings while checking the number of occurrences.
39
40     Return edited copy of the text. Assuming "whole" is really a string,
41     or something else with .replace not affecting it.
42
43     :param whole: The text to perform replacements on.
44     :param to_replace: Substring occurrences of which to replace.
45     :param replace_with: Substring to replace occurrences with.
46     :param how_many: Number of occurrences to expect.
47     :param msg: Error message to raise.
48     :param in_filename: File name in which the error occurred.
49     :type whole: str
50     :type to_replace: str
51     :type replace_with: str
52     :type how_many: int
53     :type msg: str
54     :type in_filename: str
55     :return: The whole text after replacements are done.
56     :rtype: str
57     :raise ValueError: If number of occurrences does not match.
58     """
59     found = whole.count(to_replace)
60     if found != how_many:
61         raise ValueError(f"{in_filename}: {msg}")
62     return whole.replace(to_replace, replace_with)
63
64
65 def get_iface_and_suite_id(filename):
66     """Get interface and suite ID.
67
68     Interface ID is the part of suite name
69     which should be replaced for other NIC.
70     Suite ID is the part os suite name
71     which si appended to test case names.
72
73     :param filename: Suite file.
74     :type filename: str
75     :returns: Interface ID, Suite ID.
76     :rtype: (str, str)
77     """
78     dash_split = filename.split(u"-", 1)
79     if len(dash_split[0]) <= 4:
80         # It was something like "2n1l", we need one more split.
81         dash_split = dash_split[1].split(u"-", 1)
82     return dash_split[0], dash_split[1].split(u".", 1)[0]
83
84
85 def add_default_testcases(testcase, iface, suite_id, file_out, tc_kwargs_list):
86     """Add default testcases to file.
87
88     :param testcase: Testcase class.
89     :param iface: Interface.
90     :param suite_id: Suite ID.
91     :param file_out: File to write testcases to.
92     :param tc_kwargs_list: Key-value pairs used to construct testcases.
93     :type testcase: Testcase
94     :type iface: str
95     :type suite_id: str
96     :type file_out: file
97     :type tc_kwargs_list: dict
98     """
99     # We bump tc number in any case, so that future enables/disables
100     # do not affect the numbering of other test cases.
101     for num, kwargs in enumerate(tc_kwargs_list, start=1):
102         # TODO: Is there a better way to disable some combinations?
103         emit = True
104         if kwargs[u"frame_size"] == 9000:
105             if u"vic1227" in iface:
106                 # Not supported in HW.
107                 emit = False
108             if u"vic1385" in iface:
109                 # Not supported in HW.
110                 emit = False
111             if u"ipsec" in suite_id:
112                 # IPsec code does not support chained buffers.
113                 # Tracked by Jira ticket VPP-1207.
114                 emit = False
115         if u"-16vm2t-" in suite_id or u"-16dcr2t-" in suite_id:
116             if kwargs[u"phy_cores"] > 3:
117                 # CSIT lab only has 28 (physical) core processors,
118                 # so these test would fail when attempting to assign cores.
119                 emit = False
120         if u"-24vm1t-" in suite_id or u"-24dcr1t-" in suite_id:
121             if kwargs[u"phy_cores"] > 3:
122                 # CSIT lab only has 28 (physical) core processors,
123                 # so these test would fail when attempting to assign cores.
124                 emit = False
125         if u"soak" in suite_id:
126             # Soak test take too long, do not risk other than tc01.
127             if kwargs[u"phy_cores"] != 1:
128                 emit = False
129             if kwargs[u"frame_size"] not in MIN_FRAME_SIZE_VALUES:
130                 emit = False
131         if emit:
132             file_out.write(testcase.generate(num=num, **kwargs))
133
134
135 def add_tcp_testcases(testcase, file_out, tc_kwargs_list):
136     """Add TCP testcases to file.
137
138     :param testcase: Testcase class.
139     :param file_out: File to write testcases to.
140     :param tc_kwargs_list: Key-value pairs used to construct testcases.
141     :type testcase: Testcase
142     :type file_out: file
143     :type tc_kwargs_list: dict
144     """
145     for num, kwargs in enumerate(tc_kwargs_list, start=1):
146         file_out.write(testcase.generate(num=num, **kwargs))
147
148
149 def write_default_files(in_filename, in_prolog, kwargs_list):
150     """Using given filename and prolog, write all generated suites.
151
152     :param in_filename: Template filename to derive real filenames from.
153     :param in_prolog: Template content to derive real content from.
154     :param kwargs_list: List of kwargs for add_default_testcase.
155     :type in_filename: str
156     :type in_prolog: str
157     :type kwargs_list: list of dict
158     """
159     for suite_type in Constants.PERF_TYPE_TO_KEYWORD:
160         tmp_filename = replace_defensively(
161             in_filename, u"ndrpdr", suite_type, 1,
162             u"File name should contain suite type once.", in_filename
163         )
164         tmp_prolog = replace_defensively(
165             in_prolog, u"ndrpdr".upper(), suite_type.upper(), 1,
166             u"Suite type should appear once in uppercase (as tag).",
167             in_filename
168         )
169         tmp_prolog = replace_defensively(
170             tmp_prolog,
171             u"Find NDR and PDR intervals using optimized search",
172             Constants.PERF_TYPE_TO_KEYWORD[suite_type], 1,
173             u"Main search keyword should appear once in suite.",
174             in_filename
175         )
176         tmp_prolog = replace_defensively(
177             tmp_prolog,
178             Constants.PERF_TYPE_TO_SUITE_DOC_VER[u"ndrpdr"],
179             Constants.PERF_TYPE_TO_SUITE_DOC_VER[suite_type],
180             1, u"Exact suite type doc not found.", in_filename
181         )
182         tmp_prolog = replace_defensively(
183             tmp_prolog,
184             Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER[u"ndrpdr"],
185             Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER[suite_type],
186             1, u"Exact template type doc not found.", in_filename
187         )
188         _, suite_id = get_iface_and_suite_id(tmp_filename)
189         testcase = Testcase.default(suite_id)
190         for nic_name in Constants.NIC_NAME_TO_CODE:
191             tmp2_filename = replace_defensively(
192                 tmp_filename, u"10ge2p1x710",
193                 Constants.NIC_NAME_TO_CODE[nic_name], 1,
194                 u"File name should contain NIC code once.", in_filename
195             )
196             tmp2_prolog = replace_defensively(
197                 tmp_prolog, u"Intel-X710", nic_name, 2,
198                 u"NIC name should appear twice (tag and variable).",
199                 in_filename
200             )
201             if tmp2_prolog.count(u"HW_") == 2:
202                 # TODO CSIT-1481: Crypto HW should be read
203                 # from topology file instead.
204                 if nic_name in Constants.NIC_NAME_TO_CRYPTO_HW:
205                     tmp2_prolog = replace_defensively(
206                         tmp2_prolog, u"HW_DH895xcc",
207                         Constants.NIC_NAME_TO_CRYPTO_HW[nic_name], 1,
208                         u"HW crypto name should appear.", in_filename
209                     )
210             iface, old_suite_id = get_iface_and_suite_id(tmp2_filename)
211             if u"DPDK" in in_prolog:
212                 with open(tmp2_filename, u"wt") as file_out:
213                     file_out.write(tmp2_prolog)
214                     add_default_testcases(
215                         testcase, iface, old_suite_id, file_out, kwargs_list
216                     )
217                 return
218             for driver in Constants.NIC_NAME_TO_DRIVER[nic_name]:
219                 out_filename = replace_defensively(
220                     tmp2_filename, old_suite_id,
221                     Constants.NIC_DRIVER_TO_SUITE_PREFIX[driver] + old_suite_id,
222                     1, u"Error adding driver prefix.", in_filename
223                 )
224                 out_prolog = replace_defensively(
225                     tmp2_prolog, u"vfio-pci", driver, 1,
226                     u"Driver name should appear once.", in_filename
227                 )
228                 out_prolog = replace_defensively(
229                     out_prolog, Constants.NIC_DRIVER_TO_TAG[u"vfio-pci"],
230                     Constants.NIC_DRIVER_TO_TAG[driver], 1,
231                     u"Driver tag should appear once.", in_filename
232                 )
233                 out_prolog = replace_defensively(
234                     out_prolog, Constants.NIC_DRIVER_TO_PLUGINS[u"vfio-pci"],
235                     Constants.NIC_DRIVER_TO_PLUGINS[driver], 1,
236                     u"Driver plugin should appear once.", in_filename
237                 )
238                 out_prolog = replace_defensively(
239                     out_prolog, Constants.NIC_DRIVER_TO_SETUP_ARG[u"vfio-pci"],
240                     Constants.NIC_DRIVER_TO_SETUP_ARG[driver], 1,
241                     u"Perf setup argument should appear once.", in_filename
242                 )
243                 iface, suite_id = get_iface_and_suite_id(out_filename)
244                 # TODO: Reorder loops so suite_id is finalized sooner.
245                 testcase = Testcase.default(suite_id)
246                 with open(out_filename, u"wt") as file_out:
247                     file_out.write(out_prolog)
248                     add_default_testcases(
249                         testcase, iface, suite_id, file_out, kwargs_list
250                     )
251
252
253 def write_reconf_files(in_filename, in_prolog, kwargs_list):
254     """Using given filename and prolog, write all generated reconf suites.
255
256     Use this for suite type reconf, as its local template
257     is incompatible with mrr/ndrpdr/soak local template,
258     while test cases are compatible.
259
260     :param in_filename: Template filename to derive real filenames from.
261     :param in_prolog: Template content to derive real content from.
262     :param kwargs_list: List of kwargs for add_testcase.
263     :type in_filename: str
264     :type in_prolog: str
265     :type kwargs_list: list of dict
266     """
267     _, suite_id = get_iface_and_suite_id(in_filename)
268     testcase = Testcase.default(suite_id)
269     for nic_name in Constants.NIC_NAME_TO_CODE:
270         tmp_filename = replace_defensively(
271             in_filename, u"10ge2p1x710",
272             Constants.NIC_NAME_TO_CODE[nic_name], 1,
273             u"File name should contain NIC code once.", in_filename
274         )
275         tmp_prolog = replace_defensively(
276             in_prolog, u"Intel-X710", nic_name, 2,
277             u"NIC name should appear twice (tag and variable).",
278             in_filename
279         )
280         if tmp_prolog.count(u"HW_") == 2:
281             # TODO CSIT-1481: Crypto HW should be read
282             # from topology file instead.
283             if nic_name in Constants.NIC_NAME_TO_CRYPTO_HW.keys():
284                 tmp_prolog = replace_defensively(
285                     tmp_prolog, u"HW_DH895xcc",
286                     Constants.NIC_NAME_TO_CRYPTO_HW[nic_name], 1,
287                     u"HW crypto name should appear.", in_filename
288                 )
289         iface, old_suite_id = get_iface_and_suite_id(tmp_filename)
290         for driver in Constants.NIC_NAME_TO_DRIVER[nic_name]:
291             out_filename = replace_defensively(
292                 tmp_filename, old_suite_id,
293                 Constants.NIC_DRIVER_TO_SUITE_PREFIX[driver] + old_suite_id,
294                 1, u"Error adding driver prefix.", in_filename
295             )
296             out_prolog = replace_defensively(
297                 tmp_prolog, u"vfio-pci", driver, 1,
298                 u"Driver name should appear once.", in_filename
299             )
300             out_prolog = replace_defensively(
301                 out_prolog, Constants.NIC_DRIVER_TO_TAG[u"vfio-pci"],
302                 Constants.NIC_DRIVER_TO_TAG[driver], 1,
303                 u"Driver tag should appear once.", in_filename
304             )
305             out_prolog = replace_defensively(
306                 out_prolog, Constants.NIC_DRIVER_TO_PLUGINS[u"vfio-pci"],
307                 Constants.NIC_DRIVER_TO_PLUGINS[driver], 1,
308                 u"Driver plugin should appear once.", in_filename
309             )
310             out_prolog = replace_defensively(
311                 out_prolog, Constants.NIC_DRIVER_TO_SETUP_ARG[u"vfio-pci"],
312                 Constants.NIC_DRIVER_TO_SETUP_ARG[driver], 1,
313                 u"Perf setup argument should appear once.", in_filename
314             )
315             iface, suite_id = get_iface_and_suite_id(out_filename)
316             # TODO: Reorder loops so suite_id is finalized sooner.
317             testcase = Testcase.default(suite_id)
318             with open(out_filename, u"wt") as file_out:
319                 file_out.write(out_prolog)
320                 add_default_testcases(
321                     testcase, iface, suite_id, file_out, kwargs_list
322                 )
323
324
325 def write_tcp_files(in_filename, in_prolog, kwargs_list):
326     """Using given filename and prolog, write all generated tcp suites.
327
328     TODO: Suport drivers.
329
330     :param in_filename: Template filename to derive real filenames from.
331     :param in_prolog: Template content to derive real content from.
332     :param kwargs_list: List of kwargs for add_default_testcase.
333     :type in_filename: str
334     :type in_prolog: str
335     :type kwargs_list: list of dict
336     """
337     # TODO: Generate rps from cps? There are subtle differences.
338     _, suite_id = get_iface_and_suite_id(in_filename)
339     testcase = Testcase.tcp(suite_id)
340     for nic_name in Constants.NIC_NAME_TO_CODE:
341         out_filename = replace_defensively(
342             in_filename, u"10ge2p1x710",
343             Constants.NIC_NAME_TO_CODE[nic_name], 1,
344             u"File name should contain NIC code once.", in_filename
345         )
346         out_prolog = replace_defensively(
347             in_prolog, u"Intel-X710", nic_name, 2,
348             u"NIC name should appear twice (tag and variable).",
349             in_filename
350         )
351         with open(out_filename, u"wt") as file_out:
352             file_out.write(out_prolog)
353             add_tcp_testcases(testcase, file_out, kwargs_list)
354
355
356 class Regenerator:
357     """Class containing file generating methods."""
358
359     def __init__(self, quiet=True):
360         """Initialize the instance.
361
362         :param quiet: Reduce log prints (to stderr) when True (default).
363         :type quiet: boolean
364         """
365         self.quiet = quiet
366
367     def regenerate_glob(self, pattern, protocol=u"ip4"):
368         """Regenerate files matching glob pattern based on arguments.
369
370         In the current working directory, find all files matching
371         the glob pattern. Use testcase template to regenerate test cases
372         according to suffix, governed by protocol, autonumbering them.
373         Also generate suites for other NICs and drivers.
374
375         Log-like prints are emitted to sys.stderr.
376
377         :param pattern: Glob pattern to select files. Example: *-ndrpdr.robot
378         :param protocol: String determining minimal frame size. Default: "ip4"
379         :type pattern: str
380         :type protocol: str
381         :raises RuntimeError: If invalid source suite is encountered.
382         """
383         if not self.quiet:
384             print(f"Regenerator starts at {getcwd()}", file=sys.stderr)
385
386         min_frame_size = PROTOCOL_TO_MIN_FRAME_SIZE[protocol]
387         default_kwargs_list = [
388             {u"frame_size": min_frame_size, u"phy_cores": 1},
389             {u"frame_size": min_frame_size, u"phy_cores": 2},
390             {u"frame_size": min_frame_size, u"phy_cores": 4},
391             {u"frame_size": 1518, u"phy_cores": 1},
392             {u"frame_size": 1518, u"phy_cores": 2},
393             {u"frame_size": 1518, u"phy_cores": 4},
394             {u"frame_size": 9000, u"phy_cores": 1},
395             {u"frame_size": 9000, u"phy_cores": 2},
396             {u"frame_size": 9000, u"phy_cores": 4},
397             {u"frame_size": u"IMIX_v4_1", u"phy_cores": 1},
398             {u"frame_size": u"IMIX_v4_1", u"phy_cores": 2},
399             {u"frame_size": u"IMIX_v4_1", u"phy_cores": 4}
400         ]
401         tcp_kwargs_list = [
402             {u"phy_cores": i, u"frame_size": 0} for i in (1, 2, 4)
403         ]
404         forbidden = [
405             v for v in Constants.NIC_DRIVER_TO_SUITE_PREFIX.values() if v
406         ]
407         for in_filename in glob(pattern):
408             if not self.quiet:
409                 print(
410                     u"Regenerating in_filename:", in_filename, file=sys.stderr
411                 )
412             iface, _ = get_iface_and_suite_id(in_filename)
413             if not iface.endswith(u"10ge2p1x710"):
414                 raise RuntimeError(
415                     f"Error in {in_filename}: non-primary NIC found."
416                 )
417             for prefix in forbidden:
418                 if prefix in in_filename:
419                     raise RuntimeError(
420                         f"Error in {in_filename}: non-primary driver found."
421                     )
422             with open(in_filename, u"rt") as file_in:
423                 in_prolog = u"".join(
424                     file_in.read().partition(u"*** Test Cases ***")[:-1]
425                 )
426             if in_filename.endswith(u"-ndrpdr.robot"):
427                 write_default_files(in_filename, in_prolog, default_kwargs_list)
428             elif in_filename.endswith(u"-reconf.robot"):
429                 write_reconf_files(in_filename, in_prolog, default_kwargs_list)
430             elif in_filename[-10:] in (u"-cps.robot", u"-rps.robot"):
431                 write_tcp_files(in_filename, in_prolog, tcp_kwargs_list)
432             else:
433                 raise RuntimeError(
434                     f"Error in {in_filename}: non-primary suite type found."
435                 )
436         if not self.quiet:
437             print(u"Regenerator ends.", file=sys.stderr)
438         print(file=sys.stderr)  # To make autogen check output more readable.