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