blob: 6591d16a72f3d591fb41fa9bd0d7aa1bcf646920 [file] [log] [blame]
Alex Savatieievd48994d2018-12-13 12:13:00 +01001"""Model Comparer:
2- yaml parser
3- class tree comparison
4"""
5import itertools
Alex Savatieievd48994d2018-12-13 12:13:00 +01006import os
Alex3ebc5632019-04-18 16:47:18 -05007
8from cfg_checker.common import logger, logger_cli
9from cfg_checker.reports import reporter
10
Alex Savatieievd48994d2018-12-13 12:13:00 +010011import yaml
12
Alex Savatieievd48994d2018-12-13 12:13:00 +010013
Alex3ebc5632019-04-18 16:47:18 -050014def get_element(element_path, input_data):
Alex Savatieiev4f149d02019-02-28 17:15:29 -060015 paths = element_path.split(":")
16 data = input_data
17 for i in range(0, len(paths)):
18 data = data[paths[i]]
19 return data
20
21
Alex3ebc5632019-04-18 16:47:18 -050022def pop_element(element_path, input_data):
Alex Savatieiev4f149d02019-02-28 17:15:29 -060023 paths = element_path.split(":")
24 data = input_data
25 # Search for last dict
26 for i in range(0, len(paths)-1):
27 data = data[paths[i]]
28 # pop the actual element
29 return data.pop(paths[-1])
30
31
Alex Savatieievd48994d2018-12-13 12:13:00 +010032class ModelComparer(object):
33 """Collection of functions to compare model data.
34 """
Alex Savatieiev4f149d02019-02-28 17:15:29 -060035 # key order is important
36 _model_parts = {
37 "01_nodes": "nodes",
38 "02_system": "classes:system",
39 "03_cluster": "classes:cluster",
40 "04_other": "classes"
41 }
Alex3ebc5632019-04-18 16:47:18 -050042
Alex Savatieievd48994d2018-12-13 12:13:00 +010043 models = {}
Alex Savatieiev06ab17d2019-02-26 18:40:48 -060044 models_path = "/srv/salt/reclass"
45 model_name_1 = "source"
46 model_path_1 = os.path.join(models_path, model_name_1)
47 model_name_2 = "target"
48 model_path_2 = os.path.join(models_path, model_name_1)
Alex Savatieievd48994d2018-12-13 12:13:00 +010049
50 @staticmethod
51 def load_yaml_class(fname):
52 """Loads a yaml from the file and forms a tree item
53
54 Arguments:
55 fname {string} -- full path to the yaml file
56 """
57 _yaml = {}
58 try:
59 _size = 0
60 with open(fname, 'r') as f:
Alexb8af13a2019-04-16 18:38:12 -050061 _yaml = yaml.load(f, Loader=yaml.FullLoader)
Alex Savatieievd48994d2018-12-13 12:13:00 +010062 _size = f.tell()
63 # TODO: do smth with the data
64 if not _yaml:
65 logger_cli.warning("WARN: empty file '{}'".format(fname))
66 _yaml = {}
67 else:
68 logger.debug("...loaded YAML '{}' ({}b)".format(fname, _size))
69 return _yaml
70 except yaml.YAMLError as exc:
71 logger_cli.error(exc)
72 except IOError as e:
73 logger_cli.error(
74 "Error loading file '{}': {}".format(fname, e.message)
75 )
76 raise Exception("CRITICAL: Failed to load YAML data: {}".format(
Alex Savatieiev36b938d2019-01-21 11:01:18 +010077 e.message + e.strerror
Alex Savatieievd48994d2018-12-13 12:13:00 +010078 ))
79
80 def load_model_tree(self, name, root_path="/srv/salt/reclass"):
81 """Walks supplied path for the YAML filed and loads the tree
82
83 Arguments:
84 root_folder_path {string} -- Path to Model's root folder. Optional
85 """
Alex Savatieiev42b89fa2019-03-07 18:45:26 -060086 logger_cli.info("# Loading reclass tree from '{}'".format(root_path))
Alex Savatieievd48994d2018-12-13 12:13:00 +010087 # prepare the file tree to walk
88 raw_tree = {}
89 # Credits to Andrew Clark@MIT. Original code is here:
90 # http://code.activestate.com/recipes/577879-create-a-nested-dictionary-from-oswalk/
91 root_path = root_path.rstrip(os.sep)
92 start = root_path.rfind(os.sep) + 1
93 root_key = root_path.rsplit(os.sep, 1)[1]
94 # Look Ma! I am walking the file tree with no recursion!
95 for path, dirs, files in os.walk(root_path):
96 # if this is a hidden folder, ignore it
Alex Savatieiev06ab17d2019-02-26 18:40:48 -060097 _folders_list = path[start:].split(os.sep)
98 if any(item.startswith(".") for item in _folders_list):
Alex Savatieievd48994d2018-12-13 12:13:00 +010099 continue
100 # cut absolute part of the path and split folder names
101 folders = path[start:].split(os.sep)
102 subdir = {}
103 # create generator of files that are not hidden
Alex Savatieiev36b938d2019-01-21 11:01:18 +0100104 _exts = ('.yml', '.yaml')
Alex Savatieiev06ab17d2019-02-26 18:40:48 -0600105 _subfiles = (_fl for _fl in files
106 if _fl.endswith(_exts) and not _fl.startswith('.'))
Alex Savatieievd48994d2018-12-13 12:13:00 +0100107 for _file in _subfiles:
108 # cut file extension. All reclass files are '.yml'
109 _subnode = _file
110 # load all YAML class data into the tree
111 subdir[_subnode] = self.load_yaml_class(
112 os.path.join(path, _file)
113 )
Alex Savatieiev36b938d2019-01-21 11:01:18 +0100114 try:
115 # Save original filepath, just in case
116 subdir[_subnode]["_source"] = os.path.join(
117 path[start:],
118 _file
119 )
120 except Exception:
121 logger.warning(
122 "Non-yaml file detected: {}".format(_file)
123 )
Alex Savatieievd48994d2018-12-13 12:13:00 +0100124 # creating dict structure out of folder list. Pure python magic
125 parent = reduce(dict.get, folders[:-1], raw_tree)
126 parent[folders[-1]] = subdir
Alex3ebc5632019-04-18 16:47:18 -0500127
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600128 self.models[name] = {}
129 # Brake in according to pathes
130 _parts = self._model_parts.keys()
131 _parts = sorted(_parts)
132 for ii in range(0, len(_parts)):
133 self.models[name][_parts[ii]] = pop_element(
134 self._model_parts[_parts[ii]],
135 raw_tree[root_key]
136 )
Alex3ebc5632019-04-18 16:47:18 -0500137
Alex Savatieievd48994d2018-12-13 12:13:00 +0100138 # save it as a single data object
Alex Savatieiev3db12a72019-03-22 16:32:31 -0500139 self.models[name]["rc_diffs"] = raw_tree[root_key]
Alex Savatieievd48994d2018-12-13 12:13:00 +0100140 return True
141
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600142 def find_changes(self, dict1, dict2, path=""):
143 _report = {}
144 for k in dict1.keys():
145 # yamls might load values as non-str types
146 if not isinstance(k, str):
147 _new_path = path + ":" + str(k)
148 else:
149 _new_path = path + ":" + k
150 # ignore _source key
151 if k == "_source":
152 continue
153 # check if this is an env name cluster entry
154 if dict2 is not None and \
155 k == self.model_name_1 and \
156 self.model_name_2 in dict2.keys():
157 k1 = self.model_name_1
158 k2 = self.model_name_2
159 if type(dict1[k1]) is dict:
160 if path == "":
161 _new_path = k1
162 _child_report = self.find_changes(
163 dict1[k1],
164 dict2[k2],
165 _new_path
166 )
167 _report.update(_child_report)
168 elif dict2 is None or k not in dict2:
169 # no key in dict2
170 _report[_new_path] = {
171 "type": "value",
172 "raw_values": [dict1[k], "N/A"],
173 "str_values": [
174 "{}".format(dict1[k]),
175 "n/a"
176 ]
177 }
178 logger.info(
179 "{}: {}, {}".format(_new_path, dict1[k], "N/A")
180 )
181 else:
182 if type(dict1[k]) is dict:
183 if path == "":
184 _new_path = k
185 _child_report = self.find_changes(
186 dict1[k],
187 dict2[k],
188 _new_path
189 )
190 _report.update(_child_report)
191 elif type(dict1[k]) is list and type(dict2[k]) is list:
192 # use ifilterfalse to compare lists of dicts
193 try:
194 _removed = list(
195 itertools.ifilterfalse(
196 lambda x: x in dict2[k],
197 dict1[k]
198 )
199 )
200 _added = list(
201 itertools.ifilterfalse(
202 lambda x: x in dict1[k],
203 dict2[k]
204 )
205 )
206 except TypeError as e:
207 # debug routine,
208 # should not happen, due to list check above
209 logger.error(
210 "Caught lambda type mismatch: {}".format(
211 e.message
212 )
213 )
214 logger_cli.warning(
215 "Types mismatch for correct compare: "
216 "{}, {}".format(
217 type(dict1[k]),
218 type(dict2[k])
219 )
220 )
221 _removed = None
222 _added = None
223 _original = ["= {}".format(item) for item in dict1[k]]
224 if _removed or _added:
225 _removed_str_lst = ["- {}".format(item)
226 for item in _removed]
Alex3ebc5632019-04-18 16:47:18 -0500227 _added_str_lst = ["+ {}".format(i) for i in _added]
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600228 _report[_new_path] = {
229 "type": "list",
230 "raw_values": [
231 dict1[k],
232 _removed_str_lst + _added_str_lst
233 ],
234 "str_values": [
235 "{}".format('\n'.join(_original)),
236 "{}\n{}".format(
237 '\n'.join(_removed_str_lst),
238 '\n'.join(_added_str_lst)
239 )
240 ]
241 }
242 logger.info(
243 "{}:\n"
244 "{} original items total".format(
245 _new_path,
246 len(dict1[k])
247 )
248 )
249 if _removed:
250 logger.info(
251 "{}".format('\n'.join(_removed_str_lst))
252 )
253 if _added:
254 logger.info(
255 "{}".format('\n'.join(_added_str_lst))
256 )
257 else:
258 # in case of type mismatch
259 # considering it as not equal
260 d1 = dict1
261 d2 = dict2
262 val1 = d1[k] if isinstance(d1, dict) else d1
263 val2 = d2[k] if isinstance(d2, dict) else d2
264 try:
265 match = val1 == val2
266 except TypeError as e:
267 logger.warning(
268 "One of the values is not a dict: "
269 "{}, {}".format(
270 str(dict1),
271 str(dict2)
272 ))
273 match = False
274 if not match:
275 _report[_new_path] = {
276 "type": "value",
277 "raw_values": [val1, val2],
278 "str_values": [
279 "{}".format(val1),
280 "{}".format(val2)
281 ]
282 }
283 logger.info("{}: {}, {}".format(
284 _new_path,
285 val1,
286 val2
287 ))
288 return _report
289
Alex Savatieievd48994d2018-12-13 12:13:00 +0100290 def generate_model_report_tree(self):
Alex Savatieiev0137dad2019-01-25 16:18:42 +0100291 """Use two loaded models to generate comparison table with
Alex Savatieievd48994d2018-12-13 12:13:00 +0100292 values are groupped by YAML files
293 """
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600294 # We are to cut both models into logical pieces
295 # nodes, will not be equal most of the time
296 # system, must be pretty much the same or we in trouble
297 # cluster, will be the most curious part for comparison
298 # other, all of the rest
Alex Savatieiev36b938d2019-01-21 11:01:18 +0100299
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600300 _diff_report = {}
301 for _key in self._model_parts.keys():
302 # tmp report for keys
303 _tmp_diffs = self.find_changes(
304 self.models[self.model_name_1][_key],
305 self.models[self.model_name_2][_key]
306 )
307 # prettify the report
308 for key in _tmp_diffs.keys():
309 # break the key in two parts
310 _ext = ".yml"
311 if ".yaml" in key:
312 _ext = ".yaml"
313 _split = key.split(_ext)
314 _file_path = _split[0]
315 _param_path = "none"
316 if len(_split) > 1:
317 _param_path = _split[1]
318 _tmp_diffs[key].update({
319 "class_file": _file_path + _ext,
320 "param": _param_path,
321 })
322 _diff_report[_key[3:]] = {
323 "path": self._model_parts[_key],
324 "diffs": _tmp_diffs
325 }
326
327 _diff_report["diff_names"] = [self.model_name_1, self.model_name_2]
328 return _diff_report
Alex Savatieievd48994d2018-12-13 12:13:00 +0100329
Alex Savatieievc9055712019-03-01 14:43:56 -0600330 def compare_models(self):
331 # Do actual compare using model names from the class
332 self.load_model_tree(
333 self.model_name_1,
334 self.model_path_1
335 )
336 self.load_model_tree(
337 self.model_name_2,
338 self.model_path_2
339 )
340 # Models should have similar structure to be compared
341 # classes/system
342 # classes/cluster
343 # nodes
Alex Savatieievd48994d2018-12-13 12:13:00 +0100344
Alex Savatieievc9055712019-03-01 14:43:56 -0600345 diffs = self.generate_model_report_tree()
Alex Savatieievd48994d2018-12-13 12:13:00 +0100346
Alex Savatieievc9055712019-03-01 14:43:56 -0600347 report_file = \
348 self.model_name_1 + "-vs-" + self.model_name_2 + ".html"
349 # HTML report class is post-callable
350 report = reporter.ReportToFile(
351 reporter.HTMLModelCompare(),
352 report_file
353 )
354 logger_cli.info("...generating report to {}".format(report_file))
355 # report will have tabs for each of the comparable entities in diffs
356 report({
357 "nodes": {},
Alex Savatieiev3db12a72019-03-22 16:32:31 -0500358 "rc_diffs": diffs,
Alex Savatieievc9055712019-03-01 14:43:56 -0600359 })
360 # with open("./gen_tree.json", "w+") as _out:
361 # _out.write(json.dumps(mComparer.generate_model_report_tree))
Alex Savatieiev06ab17d2019-02-26 18:40:48 -0600362
Alex Savatieievc9055712019-03-01 14:43:56 -0600363 return