FIX: do not generate 9000B perf test in case of vic1385 nic
[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 from __future__ import print_function
17
18 from glob import glob
19 from os import getcwd
20 import sys
21
22 from .DefaultTestcase import DefaultTestcase
23 from resources.libraries.python.Constants import Constants
24
25
26 # Copied from https://stackoverflow.com/a/14981125
27 def eprint(*args, **kwargs):
28     """Print to stderr."""
29     print(*args, file=sys.stderr, **kwargs)
30
31
32 class Regenerator(object):
33     """Class containing file generating methods."""
34
35     def __init__(self, testcase_class=DefaultTestcase, quiet=True):
36         """Initialize Testcase class to use.
37
38         TODO: See the type doc for testcase_class?
39         It implies the design is wrong. Fix it.
40         Easiest: Hardcode Regenerator to use DefaultTestcase only.
41
42         :param testcase_class: Subclass of DefaultTestcase for generation.
43             Default: DefaultTestcase
44         :param quiet: Reduce log prints (to stderr) when True (default).
45         :type testcase_class: subclass of DefaultTestcase accepting suite_id
46         :type quiet: boolean
47         """
48         self.testcase_class = testcase_class
49         self.quiet = quiet
50
51     def regenerate_glob(self, pattern, protocol="ip4", tc_kwargs_list=None):
52         """Regenerate files matching glob pattern based on arguments.
53
54         In the current working directory, find all files matching
55         the glob pattern. Use testcase template (from init) to regenerate
56         test cases, autonumbering them, taking arguments from list.
57         If the list is None, use default list, which depends on ip6 usage.
58
59         Log-like prints are emited to sys.stderr.
60
61         :param pattern: Glob pattern to select files. Example: *-ndrpdr.robot
62         :param is_ip6: Flag determining minimal frame size. Default: False
63         :param tc_kwargs_list: Arguments defining the testcases. Default: None
64             When None, default list is used.
65             List item is a dict, argument names are keys.
66             The initialized testcase_class should accept those, and "num".
67             DefaultTestcase accepts "frame_size" and "phy_cores".
68         :type pattern: str
69         :type is_ip6: boolean
70         :type tc_kwargs_list: list of tuple or None
71         """
72
73         protocol_to_min_frame_size = {
74             "ip4": 64,
75             "ip6": 78,
76             "vxlan+ip4": 114  # What is the real minimum for latency stream?
77         }
78         min_frame_size_values = protocol_to_min_frame_size.values()
79
80         def get_iface_and_suite_id(filename):
81             """Get interface and suite ID.
82
83             :param filename: Suite file.
84             :type filename: str
85             :returns: Interface ID, Suite ID.
86             :rtype: tuple
87             """
88             dash_split = filename.split("-", 1)
89             if len(dash_split[0]) <= 4:
90                 # It was something like "2n1l", we need one more split.
91                 dash_split = dash_split[1].split("-", 1)
92             return dash_split[0], dash_split[1].split(".", 1)[0]
93
94         def add_testcase(testcase, iface, suite_id, file_out, num, **kwargs):
95             """Add testcase to file.
96
97             :param testcase: Testcase class.
98             :param iface: Interface.
99             :param suite_id: Suite ID.
100             :param file_out: File to write testcases to.
101             :param num: Testcase number.
102             :param kwargs: Key-value pairs used to construct testcase.
103             :type testcase: Testcase
104             :type iface: str
105             :type suite_id: str
106             :type file_out: file
107             :type num: int
108             :type kwargs: dict
109             :returns: Next testcase number.
110             :rtype: int
111             """
112             # TODO: Is there a better way to disable some combinations?
113             emit = True
114             if kwargs["frame_size"] == 9000:
115                 if "vic1227" in iface:
116                     # Not supported in HW.
117                     emit = False
118                 if "vic1385" in iface:
119                     # Not supported in HW.
120                     emit = False
121                 if "avf" in suite_id:
122                     # Not supported by AVF driver.
123                     # https://git.fd.io/vpp/tree/src/plugins/avf/README.md
124                     emit = False
125             if "-16vm2t-" in suite_id or "-16dcr2t-" in suite_id:
126                 if kwargs["phy_cores"] > 3:
127                     # CSIT lab only has 28 (physical) core processors,
128                     # so these test would fail when attempting to assign cores.
129                     emit = False
130             if "-24vm1t-" in suite_id or "-24dcr1t-" in suite_id:
131                 if kwargs["phy_cores"] > 3:
132                     # CSIT lab only has 28 (physical) core processors,
133                     # so these test would fail when attempting to assign cores.
134                     emit = False
135             if "soak" in suite_id:
136                 # Soak test take too long, do not risk other than tc01.
137                 if kwargs["phy_cores"] != 1:
138                     emit = False
139                 if kwargs["frame_size"] not in min_frame_size_values:
140                     emit = False
141             if emit:
142                 file_out.write(testcase.generate(num=num, **kwargs))
143             # We bump tc number in any case, so that future enables/disables
144             # do not affect the numbering of other test cases.
145             return num + 1
146
147         def add_testcases(testcase, iface, suite_id, file_out, tc_kwargs_list):
148             """Add testcases to file.
149
150             :param testcase: Testcase class.
151             :param iface: Interface.
152             :param suite_id: Suite ID.
153             :param file_out: File to write testcases to.
154             :param tc_kwargs_list: Key-value pairs used to construct testcases.
155             :type testcase: Testcase
156             :type iface: str
157             :type suite_id: str
158             :type file_out: file
159             :type tc_kwargs_list: dict
160             """
161             num = 1
162             for tc_kwargs in tc_kwargs_list:
163                 num = add_testcase(
164                     testcase, iface, suite_id, file_out, num, **tc_kwargs)
165
166         def replace_defensively(
167                 whole, to_replace, replace_with, how_many, msg, in_filename):
168             """Replace substrings while checking the number of occurences.
169
170             Return edited copy of the text (so original string is not affected).
171
172             :param whole: The text to perform replacements on.
173             :param to_replace: Substring occurences of which to replace.
174             :param replace_with: Substring to replace occurences with.
175             :param how_many: Number of occurences to expect.
176             :param msg: Error message to raise.
177             :param in_filename: File name in which the error occured.
178             :type whole: str
179             :type to_replace: str
180             :type replace_with: str
181             :type how_many: int
182             :type msg: str
183             :type in_filename: str
184             :return: The whole text after replacements are done.
185             :rtype: str
186             :raise ValueError: If number of occurences does not match.
187             """
188             found = whole.count(to_replace)
189             if found != how_many:
190                 raise ValueError(in_filename + ": " + msg)
191             return whole.replace(to_replace, replace_with)
192
193         def write_files(in_filename, in_prolog, kwargs_list):
194             """Using given filename and prolog, write all generated suites.
195
196             :param in_filename: Template filename to derive real filenames from.
197             :param in_prolog: Template content to derive real content from.
198             :param kwargs_list: List of kwargs for add_testcase.
199             :type in_filename: str
200             :type in_prolog: str
201             :type kwargs_list: list of dict
202             """
203             for suite_type in Constants.PERF_TYPE_TO_KEYWORD.keys():
204                 tmp_filename = replace_defensively(
205                     in_filename, "ndrpdr", suite_type, 1,
206                     "File name should contain suite type once.", in_filename)
207                 tmp_prolog = replace_defensively(
208                     in_prolog, "ndrpdr".upper(), suite_type.upper(), 1,
209                     "Suite type should appear once in uppercase (as tag).",
210                     in_filename)
211                 tmp_prolog = replace_defensively(
212                     tmp_prolog,
213                     "Find NDR and PDR intervals using optimized search",
214                     Constants.PERF_TYPE_TO_KEYWORD[suite_type], 1,
215                     "Main search keyword should appear once in suite.",
216                     in_filename)
217                 tmp_prolog = replace_defensively(
218                     tmp_prolog,
219                     Constants.PERF_TYPE_TO_SUITE_DOC_VER["ndrpdr"],
220                     Constants.PERF_TYPE_TO_SUITE_DOC_VER[suite_type],
221                     1, "Exact suite type doc not found.", in_filename)
222                 tmp_prolog = replace_defensively(
223                     tmp_prolog,
224                     Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER["ndrpdr"],
225                     Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER[suite_type],
226                     1, "Exact template type doc not found.", in_filename)
227                 _, suite_id = get_iface_and_suite_id(tmp_filename)
228                 testcase = self.testcase_class(suite_id)
229                 for nic_name in Constants.NIC_NAME_TO_CODE.keys():
230                     out_filename = replace_defensively(
231                         tmp_filename, "10ge2p1x710",
232                         Constants.NIC_NAME_TO_CODE[nic_name], 1,
233                         "File name should contain NIC code once.", in_filename)
234                     out_prolog = replace_defensively(
235                         tmp_prolog, "Intel-X710", nic_name, 2,
236                         "NIC name should appear twice (tag and variable).",
237                         in_filename)
238                     if out_prolog.count("HW_") == 2:
239                         # TODO CSIT-1481: Crypto HW should be read
240                         # from topology file instead.
241                         if nic_name in Constants.NIC_NAME_TO_CRYPTO_HW.keys():
242                             out_prolog = replace_defensively(
243                                 out_prolog, "HW_DH895xcc",
244                                 Constants.NIC_NAME_TO_CRYPTO_HW[nic_name], 1,
245                                 "HW crypto name should appear.", in_filename)
246                     iface, suite_id = get_iface_and_suite_id(out_filename)
247                     with open(out_filename, "w") as file_out:
248                         file_out.write(out_prolog)
249                         add_testcases(
250                             testcase, iface, suite_id, file_out, kwargs_list)
251
252         if not self.quiet:
253             eprint("Regenerator starts at {cwd}".format(cwd=getcwd()))
254         min_frame_size = protocol_to_min_frame_size[protocol]
255         kwargs_list = tc_kwargs_list if tc_kwargs_list else [
256             {"frame_size": min_frame_size, "phy_cores": 1},
257             {"frame_size": min_frame_size, "phy_cores": 2},
258             {"frame_size": min_frame_size, "phy_cores": 4},
259             {"frame_size": 1518, "phy_cores": 1},
260             {"frame_size": 1518, "phy_cores": 2},
261             {"frame_size": 1518, "phy_cores": 4},
262             {"frame_size": 9000, "phy_cores": 1},
263             {"frame_size": 9000, "phy_cores": 2},
264             {"frame_size": 9000, "phy_cores": 4},
265             {"frame_size": "IMIX_v4_1", "phy_cores": 1},
266             {"frame_size": "IMIX_v4_1", "phy_cores": 2},
267             {"frame_size": "IMIX_v4_1", "phy_cores": 4}
268         ]
269         for in_filename in glob(pattern):
270             if not self.quiet:
271                 eprint("Regenerating in_filename:", in_filename)
272             if not in_filename.endswith("ndrpdr.robot"):
273                 eprint("Error in {fil}: non-primary suite type encountered."
274                        .format(fil=in_filename))
275                 sys.exit(1)
276             iface, _ = get_iface_and_suite_id(in_filename)
277             if not iface.endswith("10ge2p1x710"):
278                 eprint("Error in {fil}: non-primary NIC encountered."
279                        .format(fil=in_filename))
280                 sys.exit(1)
281             with open(in_filename, "r") as file_in:
282                 in_prolog = "".join(
283                     file_in.read().partition("*** Test Cases ***")[:-1])
284             write_files(in_filename, in_prolog, kwargs_list)
285         if not self.quiet:
286             eprint("Regenerator ends.")
287         eprint()  # To make autogen check output more readable.