7271fbcf379d21bdcb2b95a40ff54c46f78d631d
[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             out_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             out_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 out_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                     out_prolog = replace_defensively(
206                         out_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, suite_id = get_iface_and_suite_id(out_filename)
211             with open(out_filename, "wt") as file_out:
212                 file_out.write(out_prolog)
213                 add_default_testcases(
214                     testcase, iface, suite_id, file_out, kwargs_list
215                 )
216
217
218 def write_reconf_files(in_filename, in_prolog, kwargs_list):
219     """Using given filename and prolog, write all generated reconf suites.
220
221     Use this for suite type reconf, as its local template
222     is incompatible with mrr/ndrpdr/soak local template,
223     while test cases are compatible.
224
225     :param in_filename: Template filename to derive real filenames from.
226     :param in_prolog: Template content to derive real content from.
227     :param kwargs_list: List of kwargs for add_testcase.
228     :type in_filename: str
229     :type in_prolog: str
230     :type kwargs_list: list of dict
231     """
232     _, suite_id = get_iface_and_suite_id(in_filename)
233     testcase = Testcase.default(suite_id)
234     for nic_name in Constants.NIC_NAME_TO_CODE:
235         out_filename = replace_defensively(
236             in_filename, u"10ge2p1x710",
237             Constants.NIC_NAME_TO_CODE[nic_name], 1,
238             u"File name should contain NIC code once.", in_filename
239         )
240         out_prolog = replace_defensively(
241             in_prolog, u"Intel-X710", nic_name, 2,
242             u"NIC name should appear twice (tag and variable).",
243             in_filename
244         )
245         if out_prolog.count(u"HW_") == 2:
246             # TODO CSIT-1481: Crypto HW should be read
247             # from topology file instead.
248             if nic_name in list(Constants.NIC_NAME_TO_CRYPTO_HW.keys()):
249                 out_prolog = replace_defensively(
250                     out_prolog, u"HW_DH895xcc",
251                     Constants.NIC_NAME_TO_CRYPTO_HW[nic_name], 1,
252                     u"HW crypto name should appear.", in_filename
253                 )
254         iface, suite_id = get_iface_and_suite_id(out_filename)
255         with open(out_filename, "wt") as file_out:
256             file_out.write(out_prolog)
257             add_default_testcases(
258                 testcase, iface, suite_id, file_out, kwargs_list
259             )
260
261
262 def write_tcp_files(in_filename, in_prolog, kwargs_list):
263     """Using given filename and prolog, write all generated tcp suites.
264
265     :param in_filename: Template filename to derive real filenames from.
266     :param in_prolog: Template content to derive real content from.
267     :param kwargs_list: List of kwargs for add_default_testcase.
268     :type in_filename: str
269     :type in_prolog: str
270     :type kwargs_list: list of dict
271     """
272     # TODO: Generate rps from cps? There are subtle differences.
273     _, suite_id = get_iface_and_suite_id(in_filename)
274     testcase = Testcase.tcp(suite_id)
275     for nic_name in Constants.NIC_NAME_TO_CODE:
276         out_filename = replace_defensively(
277             in_filename, u"10ge2p1x710",
278             Constants.NIC_NAME_TO_CODE[nic_name], 1,
279             u"File name should contain NIC code once.", in_filename
280         )
281         out_prolog = replace_defensively(
282             in_prolog, u"Intel-X710", nic_name, 2,
283             u"NIC name should appear twice (tag and variable).",
284             in_filename
285         )
286         with open(out_filename, "wt") as file_out:
287             file_out.write(out_prolog)
288             add_tcp_testcases(testcase, file_out, kwargs_list)
289
290
291 class Regenerator:
292     """Class containing file generating methods."""
293
294     def __init__(self, quiet=True):
295         """Initialize the instance.
296
297         :param quiet: Reduce log prints (to stderr) when True (default).
298         :type quiet: boolean
299         """
300         self.quiet = quiet
301
302     def regenerate_glob(self, pattern, protocol=u"ip4"):
303         """Regenerate files matching glob pattern based on arguments.
304
305         In the current working directory, find all files matching
306         the glob pattern. Use testcase template according to suffix
307         to regenerate test cases, auto-numbering them,
308         taking arguments from list.
309
310         Log-like prints are emitted to sys.stderr.
311
312         :param pattern: Glob pattern to select files. Example: *-ndrpdr.robot
313         :param protocol: String determining minimal frame size. Default: "ip4"
314         :type pattern: str
315         :type protocol: str
316         :raises RuntimeError: If invalid source suite is encountered.
317         """
318         if not self.quiet:
319             print(f"Regenerator starts at {getcwd()}", file=sys.stderr)
320
321         min_frame_size = PROTOCOL_TO_MIN_FRAME_SIZE[protocol]
322         default_kwargs_list = [
323             {u"frame_size": min_frame_size, u"phy_cores": 1},
324             {u"frame_size": min_frame_size, u"phy_cores": 2},
325             {u"frame_size": min_frame_size, u"phy_cores": 4},
326             {u"frame_size": 1518, u"phy_cores": 1},
327             {u"frame_size": 1518, u"phy_cores": 2},
328             {u"frame_size": 1518, u"phy_cores": 4},
329             {u"frame_size": 9000, u"phy_cores": 1},
330             {u"frame_size": 9000, u"phy_cores": 2},
331             {u"frame_size": 9000, u"phy_cores": 4},
332             {u"frame_size": u"IMIX_v4_1", u"phy_cores": 1},
333             {u"frame_size": u"IMIX_v4_1", u"phy_cores": 2},
334             {u"frame_size": u"IMIX_v4_1", u"phy_cores": 4}
335         ]
336         tcp_kwargs_list = [
337             {u"phy_cores": i, u"frame_size": 0} for i in (1, 2, 4)
338         ]
339         for in_filename in glob(pattern):
340             if not self.quiet:
341                 print(
342                     u"Regenerating in_filename:", in_filename, file=sys.stderr
343                 )
344             iface, _ = get_iface_and_suite_id(in_filename)
345             if not iface.endswith(u"10ge2p1x710"):
346                 raise RuntimeError(
347                     f"Error in {in_filename}: non-primary NIC found."
348                 )
349             with open(in_filename, "rt") as file_in:
350                 in_prolog = u"".join(
351                     file_in.read().partition("*** Test Cases ***")[:-1]
352                 )
353             if in_filename.endswith(u"-ndrpdr.robot"):
354                 write_default_files(in_filename, in_prolog, default_kwargs_list)
355             elif in_filename.endswith(u"-reconf.robot"):
356                 write_reconf_files(in_filename, in_prolog, default_kwargs_list)
357             elif in_filename[-10:] in (u"-cps.robot", u"-rps.robot"):
358                 write_tcp_files(in_filename, in_prolog, tcp_kwargs_list)
359             else:
360                 raise RuntimeError(
361                     f"Error in {in_filename}: non-primary suite type found."
362                 )
363         if not self.quiet:
364             print(u"Regenerator ends.", file=sys.stderr)
365         print(file=sys.stderr)  # To make autogen check output more readable.