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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """Module for keeping track of VPP API CRCs relied on by CSIT."""
20 from robot.api import logger
24 """Convert from possible unicode without interpreting as number.
26 :param text: Input to convert.
27 :type text: str or unicode
28 :returns: Converted text.
31 return text.encode("utf-8") if isinstance(text, unicode) else text
34 class VppApiCrcChecker(object):
35 """Holder of data related to tracking VPP API CRCs.
37 Both message names and crc hexa strings are tracked as
38 ordinary Python2 (bytes) str, so _str() is used when input is
39 possibly unicode or otherwise not safe.
41 Each instance of this class starts with same default state,
42 so make sure the calling libraries have appropriate robot library scope.
43 For usual testing, it means "GLOBAL" scope."""
45 def __init__(self, directory):
46 """Initialize empty state, then register known collections.
48 This also scans directory for .api.json files
49 and performs initial checks, but does not report the findings yet.
51 :param directory: Root directory of the search for .api.json files.
55 self._expected = dict()
56 """Mapping from collection name to mapping from API name to CRC string.
58 Colection name should be something useful for logging.
60 Order of addition reflects the order colections should be queried.
61 If an incompatible CRC is found, affected collections are removed.
62 A CRC that would remove all does not, added to _reported instead,
63 while causing a failure in single test."""
65 self._missing = dict()
66 """Mapping from collection name to mapping from API name to CRC string.
68 Starts the same as _expected, but each time an encountered api,crc pair
69 fits the expectation, the pair is removed from this mapping.
70 Ideally, the active mappings will become empty.
71 If not, it is an error, VPP removed or renamed a message CSIT needs."""
74 """Mapping from API name to CRC string.
76 This gets populated with CRCs found in .api.json,
77 to serve as a hint when reporting errors."""
79 self._reported = dict()
80 """Mapping from API name to CRC string.
82 This gets populated with APIs used, but not found in collections,
83 just before the fact is reported in an exception.
84 The CRC comes from _found mapping (otherwise left as None).
85 The idea is to not report those next time, allowing the job
86 to find more problems in a single run."""
88 self._initial_conflicts_reported = False
90 self._check_dir(directory)
92 def _register_collection(self, collection_name, name_to_crc_mapping):
93 """Add a named (copy of) collection of CRCs.
95 :param collection_name: Helpful string describing the collection.
96 :param name_to_crc_mapping: Mapping from API names to CRCs.
97 :type collection_name: str or unicode
98 :type name_to_crc_mapping: dict from str/unicode to str/unicode
100 collection_name = _str(collection_name)
101 if collection_name in self._expected:
102 raise RuntimeError("Collection {cl!r} already registered.".format(
104 mapping = {_str(k): _str(v) for k, v in name_to_crc_mapping.items()}
105 self._expected[collection_name] = mapping
106 self._missing[collection_name] = mapping.copy()
108 def _register_all(self):
109 """Add all collections this CSIT codebase is tested against."""
111 file_path = os.path.normpath(os.path.join(
112 os.path.dirname(os.path.abspath(__file__)), "..", "..",
113 "api", "vpp", "supported_crcs.yaml"))
114 with open(file_path, "r") as file_in:
115 collections_dict = yaml.load(file_in.read())
116 for collection_name, name_to_crc_mapping in collections_dict.items():
117 self._register_collection(collection_name, name_to_crc_mapping)
120 def _get_name(msg_obj):
121 """Utility function to extract API name from an intermediate json.
123 :param msg_obj: Loaded json object, item of "messages" list.
124 :type msg_obj: list of various types
125 :returns: Name of the message.
126 :rtype: str or unicode
127 :raises RuntimeError: If no name is found.
130 if isinstance(item, (dict, list)):
133 raise RuntimeError("No name found for message: {obj!r}".format(
137 def _get_crc(msg_obj):
138 """Utility function to extract API CRC from an intermediate json.
140 :param msg_obj: Loaded json object, item of "messages" list.
141 :type msg_obj: list of various types
142 :returns: CRC of the message.
143 :rtype: str or unicode
144 :raises RuntimeError: If no CRC is found.
146 for item in reversed(msg_obj):
147 if not isinstance(item, dict):
149 crc = item.get("crc", None)
152 raise RuntimeError("No CRC found for message: {obj!r}".format(
155 def _process_crc(self, api_name, crc):
156 """Compare API to verified collections, update class state.
158 Conflict is NOT when a collection does not recognize the API.
159 Such APIs are merely added to _found for later reporting.
160 Conflict is when a collection recognizes the API under a different CRC.
161 If a partial match happens, only the matching collections are preserved.
162 On no match, all current collections are preserved,
163 but the offending API is added to _reported mapping.
165 Note that it is expected that collections are incompatible
166 with each other for some APIs. The removal of collections
167 on partial match is there to help identify the intended collection
168 for the VPP build under test. But if no collection fits perfectly,
169 the last collections to determine the "known" flag
170 depends on the order of api_name submitted,
171 which tends to be fairly random (depends on order of .api.json files).
172 Order of collection registrations does not help much in this regard.
174 Attempts to overwrite value in _found or _reported should not happen,
175 so the code does not check for that, simply overwriting.
177 The intended usage is to call this method multiple times,
178 and then raise exception listing all _reported.
180 :param api_name: API name to check.
181 :param crc: Discovered CRC to check for the name.
185 # Regardless of the result, remember as found.
186 self._found[api_name] = crc
187 old_expected = self._expected
188 new_expected = old_expected.copy()
189 for collection_name, name_to_crc_mapping in old_expected.items():
190 if api_name not in name_to_crc_mapping:
192 if name_to_crc_mapping[api_name] == crc:
193 self._missing[collection_name].pop(api_name, None)
195 # Remove the offending collection.
196 new_expected.pop(collection_name, None)
198 # Some collections recognized the CRC.
199 self._expected = new_expected
200 self._missing = {name: self._missing[name] for name in new_expected}
202 # No new_expected means some colections knew the api_name,
203 # but CRC does not match any. This has to be reported.
204 self._reported[api_name] = crc
206 def _check_dir(self, directory):
207 """Parse every .api.json found under directory, remember conflicts.
209 As several collections are supported, each conflict invalidates
210 one of them, failure happens only when no collections would be left.
211 In that case, set of collections just before the failure is preserved,
212 the _reported mapping is filled with conflicting APIs.
213 The _found mapping is filled with discovered api names and crcs.
215 The exception is not thrown here, but from report_initial_conflicts.
217 :param directory: Root directory of the search for .api.json files.
220 for root, _, files in os.walk(directory):
221 for filename in files:
222 if not filename.endswith(".api.json"):
224 with open(root + '/' + filename, "r") as file_in:
225 json_obj = json.load(file_in)
226 msgs = json_obj["messages"]
228 msg_name = self._get_name(msg_obj)
229 msg_crc = self._get_crc(msg_obj)
230 self._process_crc(msg_name, msg_crc)
231 logger.debug("Surviving collections: {col!r}".format(
232 col=self._expected.keys()))
234 def report_initial_conflicts(self, report_missing=False):
235 """Report issues discovered by _check_dir, if not done that already.
237 Intended use: Call once after init, at a time when throwing exception
240 Optionally, report also missing messages.
241 Missing reporting is disabled by default, because some messages
242 come from plugins that might not be enabled at runtime.
244 :param report_missing: Whether to raise on missing messages.
245 :type report_missing: bool
246 :raises RuntimeError: If CRC mismatch or missing messages are detected.
248 if self._initial_conflicts_reported:
250 self._initial_conflicts_reported = True
252 raise RuntimeError("Dir check found incompatible API CRCs: {rep!r}"\
253 .format(rep=self._reported))
254 if not report_missing:
256 missing = {name: mapp for name, mapp in self._missing.items() if mapp}
258 raise RuntimeError("Dir check found missing API CRCs: {mis!r}"\
259 .format(mis=missing))
261 def check_api_name(self, api_name):
262 """Fail if the api_name has no known CRC associated.
264 Do not fail if this particular failure has been already reported.
266 Intended use: Call everytime an API call is queued or response received.
268 :param api_name: VPP API messagee name to check.
269 :type api_name: str or unicode
270 :raises RuntimeError: If no verified CRC for the api_name is found.
272 api_name = _str(api_name)
273 if api_name in self._reported:
275 old_expected = self._expected
276 new_expected = old_expected.copy()
277 for collection_name, name_to_crc_mapping in old_expected.items():
278 if api_name in name_to_crc_mapping:
280 # Remove the offending collection.
281 new_expected.pop(collection_name, None)
283 # Some collections recognized the message name.
284 self._expected = new_expected
286 crc = self._found.get(api_name, None)
287 self._reported[api_name] = crc
288 # Disabled temporarily during CRC mismatch.
289 #raise RuntimeError("No active collection has API {api!r}"
290 # " CRC found {crc!r}".format(api=api_name, crc=crc))