NF_density dot1qip4udpvxlan
[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             "ethip4vxlan": 114,  # What is the real minimum for latency stream?
77             "dot1qip4vxlan": 118
78         }
79         min_frame_size_values = protocol_to_min_frame_size.values()
80
81         def get_iface_and_suite_id(filename):
82             """Get interface and suite ID.
83
84             :param filename: Suite file.
85             :type filename: str
86             :returns: Interface ID, Suite ID.
87             :rtype: tuple
88             """
89             dash_split = filename.split("-", 1)
90             if len(dash_split[0]) <= 4:
91                 # It was something like "2n1l", we need one more split.
92                 dash_split = dash_split[1].split("-", 1)
93             return dash_split[0], dash_split[1].split(".", 1)[0]
94
95         def add_testcase(testcase, iface, suite_id, file_out, num, **kwargs):
96             """Add testcase to file.
97
98             :param testcase: Testcase class.
99             :param iface: Interface.
100             :param suite_id: Suite ID.
101             :param file_out: File to write testcases to.
102             :param num: Testcase number.
103             :param kwargs: Key-value pairs used to construct testcase.
104             :type testcase: Testcase
105             :type iface: str
106             :type suite_id: str
107             :type file_out: file
108             :type num: int
109             :type kwargs: dict
110             :returns: Next testcase number.
111             :rtype: int
112             """
113             # TODO: Is there a better way to disable some combinations?
114             emit = True
115             if kwargs["frame_size"] == 9000:
116                 if "vic1227" in iface:
117                     # Not supported in HW.
118                     emit = False
119                 if "vic1385" in iface:
120                     # Not supported in HW.
121                     emit = False
122             if "-16vm2t-" in suite_id or "-16dcr2t-" in suite_id:
123                 if kwargs["phy_cores"] > 3:
124                     # CSIT lab only has 28 (physical) core processors,
125                     # so these test would fail when attempting to assign cores.
126                     emit = False
127             if "-24vm1t-" in suite_id or "-24dcr1t-" in suite_id:
128                 if kwargs["phy_cores"] > 3:
129                     # CSIT lab only has 28 (physical) core processors,
130                     # so these test would fail when attempting to assign cores.
131                     emit = False
132             if "soak" in suite_id:
133                 # Soak test take too long, do not risk other than tc01.
134                 if kwargs["phy_cores"] != 1:
135                     emit = False
136                 if kwargs["frame_size"] not in min_frame_size_values:
137                     emit = False
138             if emit:
139                 file_out.write(testcase.generate(num=num, **kwargs))
140             # We bump tc number in any case, so that future enables/disables
141             # do not affect the numbering of other test cases.
142             return num + 1
143
144         def add_testcases(testcase, iface, suite_id, file_out, tc_kwargs_list):
145             """Add testcases to file.
146
147             :param testcase: Testcase class.
148             :param iface: Interface.
149             :param suite_id: Suite ID.
150             :param file_out: File to write testcases to.
151             :param tc_kwargs_list: Key-value pairs used to construct testcases.
152             :type testcase: Testcase
153             :type iface: str
154             :type suite_id: str
155             :type file_out: file
156             :type tc_kwargs_list: dict
157             """
158             num = 1
159             for tc_kwargs in tc_kwargs_list:
160                 num = add_testcase(
161                     testcase, iface, suite_id, file_out, num, **tc_kwargs)
162
163         def replace_defensively(
164                 whole, to_replace, replace_with, how_many, msg, in_filename):
165             """Replace substrings while checking the number of occurences.
166
167             Return edited copy of the text (so original string is not affected).
168
169             :param whole: The text to perform replacements on.
170             :param to_replace: Substring occurences of which to replace.
171             :param replace_with: Substring to replace occurences with.
172             :param how_many: Number of occurences to expect.
173             :param msg: Error message to raise.
174             :param in_filename: File name in which the error occured.
175             :type whole: str
176             :type to_replace: str
177             :type replace_with: str
178             :type how_many: int
179             :type msg: str
180             :type in_filename: str
181             :return: The whole text after replacements are done.
182             :rtype: str
183             :raise ValueError: If number of occurences does not match.
184             """
185             found = whole.count(to_replace)
186             if found != how_many:
187                 raise ValueError(in_filename + ": " + msg)
188             return whole.replace(to_replace, replace_with)
189
190         def write_files(in_filename, in_prolog, kwargs_list):
191             """Using given filename and prolog, write all generated suites.
192
193             :param in_filename: Template filename to derive real filenames from.
194             :param in_prolog: Template content to derive real content from.
195             :param kwargs_list: List of kwargs for add_testcase.
196             :type in_filename: str
197             :type in_prolog: str
198             :type kwargs_list: list of dict
199             """
200             for suite_type in Constants.PERF_TYPE_TO_KEYWORD.keys():
201                 tmp_filename = replace_defensively(
202                     in_filename, "ndrpdr", suite_type, 1,
203                     "File name should contain suite type once.", in_filename)
204                 tmp_prolog = replace_defensively(
205                     in_prolog, "ndrpdr".upper(), suite_type.upper(), 1,
206                     "Suite type should appear once in uppercase (as tag).",
207                     in_filename)
208                 tmp_prolog = replace_defensively(
209                     tmp_prolog,
210                     "Find NDR and PDR intervals using optimized search",
211                     Constants.PERF_TYPE_TO_KEYWORD[suite_type], 1,
212                     "Main search keyword should appear once in suite.",
213                     in_filename)
214                 tmp_prolog = replace_defensively(
215                     tmp_prolog,
216                     Constants.PERF_TYPE_TO_SUITE_DOC_VER["ndrpdr"],
217                     Constants.PERF_TYPE_TO_SUITE_DOC_VER[suite_type],
218                     1, "Exact suite type doc not found.", in_filename)
219                 tmp_prolog = replace_defensively(
220                     tmp_prolog,
221                     Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER["ndrpdr"],
222                     Constants.PERF_TYPE_TO_TEMPLATE_DOC_VER[suite_type],
223                     1, "Exact template type doc not found.", in_filename)
224                 _, suite_id = get_iface_and_suite_id(tmp_filename)
225                 testcase = self.testcase_class(suite_id)
226                 for nic_name in Constants.NIC_NAME_TO_CODE.keys():
227                     out_filename = replace_defensively(
228                         tmp_filename, "10ge2p1x710",
229                         Constants.NIC_NAME_TO_CODE[nic_name], 1,
230                         "File name should contain NIC code once.", in_filename)
231                     out_prolog = replace_defensively(
232                         tmp_prolog, "Intel-X710", nic_name, 2,
233                         "NIC name should appear twice (tag and variable).",
234                         in_filename)
235                     if out_prolog.count("HW_") == 2:
236                         # TODO CSIT-1481: Crypto HW should be read
237                         # from topology file instead.
238                         if nic_name in Constants.NIC_NAME_TO_CRYPTO_HW.keys():
239                             out_prolog = replace_defensively(
240                                 out_prolog, "HW_DH895xcc",
241                                 Constants.NIC_NAME_TO_CRYPTO_HW[nic_name], 1,
242                                 "HW crypto name should appear.", in_filename)
243                     iface, suite_id = get_iface_and_suite_id(out_filename)
244                     with open(out_filename, "w") as file_out:
245                         file_out.write(out_prolog)
246                         add_testcases(
247                             testcase, iface, suite_id, file_out, kwargs_list)
248
249         if not self.quiet:
250             eprint("Regenerator starts at {cwd}".format(cwd=getcwd()))
251         min_frame_size = protocol_to_min_frame_size[protocol]
252         kwargs_list = tc_kwargs_list if tc_kwargs_list else [
253             {"frame_size": min_frame_size, "phy_cores": 1},
254             {"frame_size": min_frame_size, "phy_cores": 2},
255             {"frame_size": min_frame_size, "phy_cores": 4},
256             {"frame_size": 1518, "phy_cores": 1},
257             {"frame_size": 1518, "phy_cores": 2},
258             {"frame_size": 1518, "phy_cores": 4},
259             {"frame_size": 9000, "phy_cores": 1},
260             {"frame_size": 9000, "phy_cores": 2},
261             {"frame_size": 9000, "phy_cores": 4},
262             {"frame_size": "IMIX_v4_1", "phy_cores": 1},
263             {"frame_size": "IMIX_v4_1", "phy_cores": 2},
264             {"frame_size": "IMIX_v4_1", "phy_cores": 4}
265         ]
266         for in_filename in glob(pattern):
267             if not self.quiet:
268                 eprint("Regenerating in_filename:", in_filename)
269             if not in_filename.endswith("ndrpdr.robot"):
270                 eprint("Error in {fil}: non-primary suite type encountered."
271                        .format(fil=in_filename))
272                 sys.exit(1)
273             iface, _ = get_iface_and_suite_id(in_filename)
274             if not iface.endswith("10ge2p1x710"):
275                 eprint("Error in {fil}: non-primary NIC encountered."
276                        .format(fil=in_filename))
277                 sys.exit(1)
278             with open(in_filename, "r") as file_in:
279                 in_prolog = "".join(
280                     file_in.read().partition("*** Test Cases ***")[:-1])
281             write_files(in_filename, in_prolog, kwargs_list)
282         if not self.quiet:
283             eprint("Regenerator ends.")
284         eprint()  # To make autogen check output more readable.