blob: 47e4bafbab3a127238e3a0db2439c1ed7cda821d [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
Alex3bc95f62020-03-05 17:00:04 -06008from functools import reduce
9
Alex3ebc5632019-04-18 16:47:18 -050010from cfg_checker.common import logger, logger_cli
Alex3ebc5632019-04-18 16:47:18 -050011
Alex Savatieievd48994d2018-12-13 12:13:00 +010012import yaml
13
Alex Savatieievd48994d2018-12-13 12:13:00 +010014
Alex3ebc5632019-04-18 16:47:18 -050015def get_element(element_path, input_data):
Alex Savatieiev4f149d02019-02-28 17:15:29 -060016 paths = element_path.split(":")
17 data = input_data
18 for i in range(0, len(paths)):
19 data = data[paths[i]]
20 return data
21
22
Alex3ebc5632019-04-18 16:47:18 -050023def pop_element(element_path, input_data):
Alex Savatieiev4f149d02019-02-28 17:15:29 -060024 paths = element_path.split(":")
25 data = input_data
26 # Search for last dict
27 for i in range(0, len(paths)-1):
28 data = data[paths[i]]
29 # pop the actual element
30 return data.pop(paths[-1])
31
32
Alex Savatieievd48994d2018-12-13 12:13:00 +010033class ModelComparer(object):
34 """Collection of functions to compare model data.
35 """
Alex Savatieiev4f149d02019-02-28 17:15:29 -060036 # key order is important
37 _model_parts = {
38 "01_nodes": "nodes",
39 "02_system": "classes:system",
40 "03_cluster": "classes:cluster",
41 "04_other": "classes"
42 }
Alex3ebc5632019-04-18 16:47:18 -050043
Alex Savatieievd48994d2018-12-13 12:13:00 +010044 models = {}
Alex Savatieiev06ab17d2019-02-26 18:40:48 -060045 models_path = "/srv/salt/reclass"
46 model_name_1 = "source"
47 model_path_1 = os.path.join(models_path, model_name_1)
48 model_name_2 = "target"
49 model_path_2 = os.path.join(models_path, model_name_1)
Alex Savatieievd48994d2018-12-13 12:13:00 +010050
51 @staticmethod
52 def load_yaml_class(fname):
53 """Loads a yaml from the file and forms a tree item
54
55 Arguments:
56 fname {string} -- full path to the yaml file
57 """
58 _yaml = {}
59 try:
60 _size = 0
61 with open(fname, 'r') as f:
Alexb8af13a2019-04-16 18:38:12 -050062 _yaml = yaml.load(f, Loader=yaml.FullLoader)
Alex Savatieievd48994d2018-12-13 12:13:00 +010063 _size = f.tell()
64 # TODO: do smth with the data
65 if not _yaml:
Alex1839bbf2019-08-22 17:17:21 -050066 # logger.warning("WARN: empty file '{}'".format(fname))
Alex Savatieievd48994d2018-12-13 12:13:00 +010067 _yaml = {}
68 else:
69 logger.debug("...loaded YAML '{}' ({}b)".format(fname, _size))
70 return _yaml
71 except yaml.YAMLError as exc:
72 logger_cli.error(exc)
73 except IOError as e:
74 logger_cli.error(
75 "Error loading file '{}': {}".format(fname, e.message)
76 )
77 raise Exception("CRITICAL: Failed to load YAML data: {}".format(
Alex Savatieiev36b938d2019-01-21 11:01:18 +010078 e.message + e.strerror
Alex Savatieievd48994d2018-12-13 12:13:00 +010079 ))
80
81 def load_model_tree(self, name, root_path="/srv/salt/reclass"):
82 """Walks supplied path for the YAML filed and loads the tree
83
84 Arguments:
85 root_folder_path {string} -- Path to Model's root folder. Optional
86 """
Alex Savatieiev42b89fa2019-03-07 18:45:26 -060087 logger_cli.info("# Loading reclass tree from '{}'".format(root_path))
Alex Savatieievd48994d2018-12-13 12:13:00 +010088 # prepare the file tree to walk
89 raw_tree = {}
90 # Credits to Andrew Clark@MIT. Original code is here:
91 # http://code.activestate.com/recipes/577879-create-a-nested-dictionary-from-oswalk/
92 root_path = root_path.rstrip(os.sep)
93 start = root_path.rfind(os.sep) + 1
94 root_key = root_path.rsplit(os.sep, 1)[1]
95 # Look Ma! I am walking the file tree with no recursion!
96 for path, dirs, files in os.walk(root_path):
97 # if this is a hidden folder, ignore it
Alex Savatieiev06ab17d2019-02-26 18:40:48 -060098 _folders_list = path[start:].split(os.sep)
99 if any(item.startswith(".") for item in _folders_list):
Alex Savatieievd48994d2018-12-13 12:13:00 +0100100 continue
101 # cut absolute part of the path and split folder names
102 folders = path[start:].split(os.sep)
103 subdir = {}
104 # create generator of files that are not hidden
Alex Savatieiev36b938d2019-01-21 11:01:18 +0100105 _exts = ('.yml', '.yaml')
Alex Savatieiev06ab17d2019-02-26 18:40:48 -0600106 _subfiles = (_fl for _fl in files
107 if _fl.endswith(_exts) and not _fl.startswith('.'))
Alex Savatieievd48994d2018-12-13 12:13:00 +0100108 for _file in _subfiles:
109 # cut file extension. All reclass files are '.yml'
110 _subnode = _file
111 # load all YAML class data into the tree
112 subdir[_subnode] = self.load_yaml_class(
113 os.path.join(path, _file)
114 )
Alex Savatieiev36b938d2019-01-21 11:01:18 +0100115 try:
116 # Save original filepath, just in case
117 subdir[_subnode]["_source"] = os.path.join(
118 path[start:],
119 _file
120 )
121 except Exception:
122 logger.warning(
123 "Non-yaml file detected: {}".format(_file)
124 )
Alex Savatieievd48994d2018-12-13 12:13:00 +0100125 # creating dict structure out of folder list. Pure python magic
126 parent = reduce(dict.get, folders[:-1], raw_tree)
127 parent[folders[-1]] = subdir
Alex3ebc5632019-04-18 16:47:18 -0500128
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600129 self.models[name] = {}
130 # Brake in according to pathes
131 _parts = self._model_parts.keys()
132 _parts = sorted(_parts)
133 for ii in range(0, len(_parts)):
134 self.models[name][_parts[ii]] = pop_element(
135 self._model_parts[_parts[ii]],
136 raw_tree[root_key]
137 )
Alex3ebc5632019-04-18 16:47:18 -0500138
Alex Savatieievd48994d2018-12-13 12:13:00 +0100139 # save it as a single data object
Alex Savatieiev3db12a72019-03-22 16:32:31 -0500140 self.models[name]["rc_diffs"] = raw_tree[root_key]
Alex Savatieievd48994d2018-12-13 12:13:00 +0100141 return True
142
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600143 def find_changes(self, dict1, dict2, path=""):
144 _report = {}
145 for k in dict1.keys():
146 # yamls might load values as non-str types
147 if not isinstance(k, str):
148 _new_path = path + ":" + str(k)
149 else:
150 _new_path = path + ":" + k
151 # ignore _source key
152 if k == "_source":
153 continue
Alex1839bbf2019-08-22 17:17:21 -0500154 # ignore secrets
155 if isinstance(k, str) and k == "secrets.yml":
156 continue
157 if isinstance(k, str) and k.find("_password") > 0:
158 continue
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600159 # check if this is an env name cluster entry
160 if dict2 is not None and \
161 k == self.model_name_1 and \
162 self.model_name_2 in dict2.keys():
163 k1 = self.model_name_1
164 k2 = self.model_name_2
165 if type(dict1[k1]) is dict:
166 if path == "":
167 _new_path = k1
168 _child_report = self.find_changes(
169 dict1[k1],
170 dict2[k2],
171 _new_path
172 )
173 _report.update(_child_report)
174 elif dict2 is None or k not in dict2:
175 # no key in dict2
176 _report[_new_path] = {
177 "type": "value",
178 "raw_values": [dict1[k], "N/A"],
179 "str_values": [
180 "{}".format(dict1[k]),
181 "n/a"
182 ]
183 }
184 logger.info(
185 "{}: {}, {}".format(_new_path, dict1[k], "N/A")
186 )
187 else:
188 if type(dict1[k]) is dict:
189 if path == "":
190 _new_path = k
191 _child_report = self.find_changes(
192 dict1[k],
193 dict2[k],
194 _new_path
195 )
196 _report.update(_child_report)
197 elif type(dict1[k]) is list and type(dict2[k]) is list:
198 # use ifilterfalse to compare lists of dicts
199 try:
200 _removed = list(
Alex3bc95f62020-03-05 17:00:04 -0600201 itertools.filterfalse(
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600202 lambda x: x in dict2[k],
203 dict1[k]
204 )
205 )
206 _added = list(
Alex3bc95f62020-03-05 17:00:04 -0600207 itertools.filterfalse(
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600208 lambda x: x in dict1[k],
209 dict2[k]
210 )
211 )
212 except TypeError as e:
213 # debug routine,
214 # should not happen, due to list check above
215 logger.error(
216 "Caught lambda type mismatch: {}".format(
217 e.message
218 )
219 )
220 logger_cli.warning(
221 "Types mismatch for correct compare: "
222 "{}, {}".format(
223 type(dict1[k]),
224 type(dict2[k])
225 )
226 )
227 _removed = None
228 _added = None
229 _original = ["= {}".format(item) for item in dict1[k]]
230 if _removed or _added:
231 _removed_str_lst = ["- {}".format(item)
232 for item in _removed]
Alex3ebc5632019-04-18 16:47:18 -0500233 _added_str_lst = ["+ {}".format(i) for i in _added]
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600234 _report[_new_path] = {
235 "type": "list",
236 "raw_values": [
237 dict1[k],
238 _removed_str_lst + _added_str_lst
239 ],
240 "str_values": [
241 "{}".format('\n'.join(_original)),
242 "{}\n{}".format(
243 '\n'.join(_removed_str_lst),
244 '\n'.join(_added_str_lst)
245 )
246 ]
247 }
248 logger.info(
249 "{}:\n"
250 "{} original items total".format(
251 _new_path,
252 len(dict1[k])
253 )
254 )
255 if _removed:
256 logger.info(
257 "{}".format('\n'.join(_removed_str_lst))
258 )
259 if _added:
260 logger.info(
261 "{}".format('\n'.join(_added_str_lst))
262 )
263 else:
264 # in case of type mismatch
265 # considering it as not equal
266 d1 = dict1
267 d2 = dict2
268 val1 = d1[k] if isinstance(d1, dict) else d1
269 val2 = d2[k] if isinstance(d2, dict) else d2
270 try:
271 match = val1 == val2
272 except TypeError as e:
273 logger.warning(
274 "One of the values is not a dict: "
Alex3bc95f62020-03-05 17:00:04 -0600275 "{}, {}; {}".format(
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600276 str(dict1),
Alex3bc95f62020-03-05 17:00:04 -0600277 str(dict2),
278 e.message
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600279 ))
280 match = False
281 if not match:
282 _report[_new_path] = {
283 "type": "value",
284 "raw_values": [val1, val2],
285 "str_values": [
286 "{}".format(val1),
287 "{}".format(val2)
288 ]
289 }
290 logger.info("{}: {}, {}".format(
291 _new_path,
292 val1,
293 val2
294 ))
295 return _report
296
Alex Savatieievd48994d2018-12-13 12:13:00 +0100297 def generate_model_report_tree(self):
Alex Savatieiev0137dad2019-01-25 16:18:42 +0100298 """Use two loaded models to generate comparison table with
Alex Savatieievd48994d2018-12-13 12:13:00 +0100299 values are groupped by YAML files
300 """
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600301 # We are to cut both models into logical pieces
302 # nodes, will not be equal most of the time
303 # system, must be pretty much the same or we in trouble
304 # cluster, will be the most curious part for comparison
305 # other, all of the rest
Alex Savatieiev36b938d2019-01-21 11:01:18 +0100306
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600307 _diff_report = {}
308 for _key in self._model_parts.keys():
309 # tmp report for keys
310 _tmp_diffs = self.find_changes(
311 self.models[self.model_name_1][_key],
312 self.models[self.model_name_2][_key]
313 )
314 # prettify the report
315 for key in _tmp_diffs.keys():
316 # break the key in two parts
317 _ext = ".yml"
318 if ".yaml" in key:
319 _ext = ".yaml"
320 _split = key.split(_ext)
321 _file_path = _split[0]
322 _param_path = "none"
323 if len(_split) > 1:
324 _param_path = _split[1]
325 _tmp_diffs[key].update({
326 "class_file": _file_path + _ext,
327 "param": _param_path,
328 })
329 _diff_report[_key[3:]] = {
330 "path": self._model_parts[_key],
331 "diffs": _tmp_diffs
332 }
333
334 _diff_report["diff_names"] = [self.model_name_1, self.model_name_2]
335 return _diff_report