feat(jobspec): Unify soak jobspecs
[csit.git] / resources / libraries / python / VppApiCrc.py
1 # Copyright (c) 2021 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 for keeping track of VPP API CRCs relied on by CSIT."""
15
16 import json
17 import os
18 import yaml
19
20 from robot.api import logger
21
22 from resources.libraries.python.Constants import Constants
23
24
25 def _str(text):
26     """Convert from possible bytes without interpreting as number.
27
28     :param text: Input to convert.
29     :type text: str or unicode
30     :returns: Converted text.
31     :rtype: str
32     """
33     return text.decode(u"utf-8") if isinstance(text, bytes) else text
34
35
36 class VppApiCrcChecker:
37     """Holder of data related to tracking VPP API CRCs.
38
39     Both message names and crc hexa strings are tracked as
40     ordinary Python3 (unicode) string, so _str() is used when input is
41     possibly bytes or otherwise not safe.
42
43     Each instance of this class starts with same default state,
44     so make sure the calling libraries have appropriate robot library scope.
45     For usual testing, it means "GLOBAL" scope."""
46
47     def __init__(
48             self, directory, fail_on_mismatch=Constants.FAIL_ON_CRC_MISMATCH):
49         """Initialize empty state, then register known collections.
50
51         This also scans directory for .api.json files
52         and performs initial checks, but does not report the findings yet.
53
54         :param directory: Root directory of the search for .api.json files.
55         :type directory: str
56         """
57
58         self.fail_on_mismatch = fail_on_mismatch
59         """If True, mismatch leads to test failure, by raising exception.
60         If False, the mismatch is logged, but the test is allowed to continue.
61         """
62
63         self._expected = dict()
64         """Mapping from collection name to mapping from API name to CRC string.
65
66         Collection name should be something useful for logging.
67
68         Order of addition reflects the order collections should be queried.
69         If an incompatible CRC is found, affected collections are removed.
70         A CRC that would remove all does not, added to _reported instead,
71         while causing a failure in single test (if fail_on_mismatch)."""
72
73         self._missing = dict()
74         """Mapping from collection name to mapping from API name to CRC string.
75
76         Starts the same as _expected, but each time an encountered api,crc pair
77         fits the expectation, the pair is removed from all collections
78         within this mapping. Ideally, the active mappings will become empty.
79         If not, it is an error, VPP removed or renamed a message CSIT needs."""
80
81         self._found = dict()
82         """Mapping from API name to CRC string.
83
84         This gets populated with CRCs found in .api.json,
85         to serve as a hint when reporting errors."""
86
87         self._options = dict()
88         """Mapping from API name to options dictionary.
89
90         This gets populated with options found in .api.json,
91         to serve as a hint when reporting errors."""
92
93         self._reported = dict()
94         """Mapping from API name to CRC string.
95
96         This gets populated with APIs used, but not found in collections,
97         just before the fact is reported in an exception.
98         The CRC comes from _found mapping (otherwise left as None).
99         The idea is to not report those next time, allowing the job
100         to find more problems in a single run."""
101
102         self._initial_conflicts_reported = False
103         self._register_all()
104         self._check_dir(directory)
105
106     def log_and_raise(self, exc_msg):
107         """Log to console, on fail_on_mismatch also raise runtime exception.
108
109         :param exc_msg: The message to include in log or exception.
110         :type exc_msg: str
111         :raises RuntimeError: With the message, if fail_on_mismatch.
112         """
113         logger.console("RuntimeError:\n{m}".format(m=exc_msg))
114         if self.fail_on_mismatch:
115             raise RuntimeError(exc_msg)
116
117     def _register_collection(self, collection_name, name_to_crc_mapping):
118         """Add a named (copy of) collection of CRCs.
119
120         :param collection_name: Helpful string describing the collection.
121         :param name_to_crc_mapping: Mapping from API names to CRCs.
122         :type collection_name: str or unicode
123         :type name_to_crc_mapping: dict from str/unicode to str/unicode
124         :raises RuntimeError: If the name of a collection is registered already.
125         """
126         collection_name = _str(collection_name)
127         if collection_name in self._expected:
128             raise RuntimeError(
129                 f"Collection {collection_name!r} already registered."
130             )
131         mapping = {_str(k): _str(v) for k, v in name_to_crc_mapping.items()}
132         self._expected[collection_name] = mapping
133         self._missing[collection_name] = mapping.copy()
134
135     def _register_all(self):
136         """Add all collections this CSIT codebase is tested against."""
137
138         file_path = os.path.normpath(os.path.join(
139             os.path.dirname(os.path.abspath(__file__)), u"..", u"..",
140             u"api", u"vpp", u"supported_crcs.yaml"))
141         with open(file_path, u"rt") as file_in:
142             collections_dict = yaml.safe_load(file_in.read())
143         for collection_name, name_to_crc_mapping in collections_dict.items():
144             self._register_collection(collection_name, name_to_crc_mapping)
145
146     @staticmethod
147     def _get_name(msg_obj):
148         """Utility function to extract API name from an intermediate json.
149
150         :param msg_obj: Loaded json object, item of "messages" list.
151         :type msg_obj: list of various types
152         :returns: Name of the message.
153         :rtype: str or unicode
154         :raises RuntimeError: If no name is found.
155         """
156         for item in msg_obj:
157             if isinstance(item, (dict, list)):
158                 continue
159             return _str(item)
160         raise RuntimeError(f"No name found for message: {msg_obj!r}")
161
162     @staticmethod
163     def _get_crc(msg_obj):
164         """Utility function to extract API CRC from an intermediate json.
165
166         :param msg_obj: Loaded json object, item of "messages" list.
167         :type msg_obj: list of various types
168         :returns: CRC of the message.
169         :rtype: str or unicode
170         :raises RuntimeError: If no CRC is found.
171         """
172         for item in reversed(msg_obj):
173             if not isinstance(item, dict):
174                 continue
175             crc = item.get(u"crc", None)
176             if crc:
177                 return _str(crc)
178         raise RuntimeError(f"No CRC found for message: {msg_obj!r}")
179
180     @staticmethod
181     def _get_options(msg_obj, version):
182         """Utility function to extract API options from an intermediate json.
183
184         Empty dict is returned if options are not found,
185         so old VPP builds can be tested without spamming.
186         If version starts with "0.", add a fake option,
187         as the message is treated as "in-progress" by the API upgrade process.
188
189         :param msg_obj: Loaded json object, item of "messages" list.
190         :param version: Version string from the .api.json file.
191         :type msg_obj: list of various types
192         :type version: Optional[str]
193         :returns: Object found as value for "options" key.
194         :rtype: dict
195         """
196         options = dict()
197         for item in reversed(msg_obj):
198             if not isinstance(item, dict):
199                 continue
200             options = item.get(u"options", dict())
201             if not options:
202                 break
203         if version is None or version.startswith(u"0."):
204             options[u"version"] = version
205         return options
206
207     def _process_crc(self, api_name, crc, options):
208         """Compare API to verified collections, update class state.
209
210         Here, API stands for (message name, CRC) pair.
211
212         Conflict is NOT when a collection does not recognize the API.
213         Such APIs are merely added to _found for later reporting.
214         Conflict is when a collection recognizes the API under a different CRC.
215         If a partial match happens, only the matching collections are preserved.
216         On no match, all current collections are preserved,
217         but the offending API is added to _reported mapping.
218
219         Note that it is expected that collections are incompatible
220         with each other for some APIs. The removal of collections
221         on partial match is there to help identify the intended collection
222         for the VPP build under test. But if no collection fits perfectly,
223         the last collections to determine the "known" flag
224         depends on the order of api_name submitted,
225         which tends to be fairly random (depends on order of .api.json files).
226         Order of collection registrations does not help much in this regard.
227
228         Attempts to overwrite value in _found or _reported should not happen,
229         so the code does not check for that, simply overwriting.
230
231         Options are stored, to be examined later.
232
233         The intended usage is to call this method multiple times,
234         and then raise exception listing all _reported.
235
236         :param api_name: API name to check.
237         :param crc: Discovered CRC to check for the name.
238         :param options: Empty dict or options value for in .api.json
239         :type api_name: str
240         :type crc: str
241         :type options: dict
242         """
243         # Regardless of the result, remember as found.
244         self._found[api_name] = crc
245         self._options[api_name] = options
246         old_expected = self._expected
247         new_expected = old_expected.copy()
248         for collection_name, name_to_crc_mapping in old_expected.items():
249             if api_name not in name_to_crc_mapping:
250                 continue
251             if name_to_crc_mapping[api_name] == crc:
252                 self._missing[collection_name].pop(api_name, None)
253                 continue
254             # Remove the offending collection.
255             new_expected.pop(collection_name, None)
256         if new_expected:
257             # Some collections recognized the CRC.
258             self._expected = new_expected
259             self._missing = {name: self._missing[name] for name in new_expected}
260             return
261         # No new_expected means some collections knew the api_name,
262         # but CRC does not match any. This has to be reported.
263         self._reported[api_name] = crc
264
265     def _check_dir(self, directory):
266         """Parse every .api.json found under directory, remember conflicts.
267
268         As several collections are supported, each conflict invalidates
269         some of them, failure happens only when no collections would be left.
270         In that case, set of collections just before the failure is preserved,
271         the _reported mapping is filled with conflicting APIs.
272         The _found mapping is filled with discovered api names and crcs.
273
274         The exception is not thrown here, but from report_initial_conflicts.
275
276         :param directory: Root directory of the search for .api.json files.
277         :type directory: str
278         """
279         for root, _, files in os.walk(directory):
280             for filename in files:
281                 if not filename.endswith(u".api.json"):
282                     continue
283                 with open(f"{root}/{filename}", u"rt") as file_in:
284                     json_obj = json.load(file_in)
285                 version = json_obj[u"options"].get(u"version", None)
286                 msgs = json_obj[u"messages"]
287                 for msg_obj in msgs:
288                     msg_name = self._get_name(msg_obj)
289                     msg_crc = self._get_crc(msg_obj)
290                     msg_options = self._get_options(msg_obj, version)
291                     self._process_crc(msg_name, msg_crc, msg_options)
292         logger.debug(f"Surviving collections: {self._expected.keys()!r}")
293
294     def report_initial_conflicts(self, report_missing=False):
295         """Report issues discovered by _check_dir, if not done that already.
296
297         Intended use: Call once after init, at a time when throwing exception
298         is convenient.
299
300         Optionally, report also missing messages.
301         Missing reporting is disabled by default, because some messages
302         come from plugins that might not be enabled at runtime.
303
304         After the report, clear _reported, so that test cases report them again,
305         thus tracking which message is actually used (by which test).
306
307         :param report_missing: Whether to raise on missing messages.
308         :type report_missing: bool
309         :raises RuntimeError: If CRC mismatch or missing messages are detected,
310             and fail_on_mismatch is True.
311         """
312         if self._initial_conflicts_reported:
313             return
314         self._initial_conflicts_reported = True
315         if self._reported:
316             reported_indented = json.dumps(
317                 self._reported, indent=1, sort_keys=True,
318                 separators=[u",", u":"]
319             )
320             self._reported = dict()
321             self.log_and_raise(
322                 f"Incompatible API CRCs found in .api.json files:\n"
323                 f"{reported_indented}"
324             )
325         if not report_missing:
326             return
327         missing = {name: mapp for name, mapp in self._missing.items() if mapp}
328         if missing:
329             missing_indented = json.dumps(
330                 missing, indent=1, sort_keys=True, separators=[u",", u":"])
331             self.log_and_raise(
332                 f"API CRCs missing from .api.json:\n{missing_indented}"
333             )
334
335     def check_api_name(self, api_name):
336         """Fail if the api_name has no, or different from known CRC associated.
337
338         Print warning if options contain anything more than vat_help.
339
340         Do not fail if this particular failure has been already reported.
341
342         Intended use: Call during test (not in initialization),
343         every time an API call is queued or response received.
344
345         :param api_name: VPP API message name to check.
346         :type api_name: str or unicode
347         :raises RuntimeError: If no verified CRC for the api_name is found.
348         """
349         api_name = _str(api_name)
350         if api_name in self._reported:
351             return
352         old_expected = self._expected
353         new_expected = old_expected.copy()
354         for collection_name, name_to_crc_mapping in old_expected.items():
355             if api_name in name_to_crc_mapping:
356                 continue
357             # Remove the offending collection.
358             new_expected.pop(collection_name, None)
359         if new_expected:
360             # Some collections recognized the message name.
361             self._expected = new_expected
362         crc = self._found.get(api_name, None)
363         matching = False
364         if crc is not None:
365             # Regardless of how many collections are remaining,
366             # verify the known CRC is on one of them.
367             for name_to_crc_mapping in self._expected.values():
368                 if api_name not in name_to_crc_mapping:
369                     continue
370                 if name_to_crc_mapping[api_name] == crc:
371                     matching = True
372                     break
373         if not matching:
374             self._reported[api_name] = crc
375             self.log_and_raise(
376                 f"No active collection has API {api_name!r} with CRC {crc!r}"
377             )
378         options = self._options[api_name]
379         options.pop(u"vat_help", None)
380         if options:
381             self._reported[api_name] = crc
382             logger.console(f"{api_name} used but has options {options}")