blob: 9cac4f57bd43f1aa9396c3715aa4692440fd2114 [file] [log] [blame]
savex4448e132018-04-25 15:51:14 +02001import abc
2import os
Alex1839bbf2019-08-22 17:17:21 -05003import re
Alex41485522019-04-12 17:26:18 -05004import time
savex4448e132018-04-25 15:51:14 +02005
Alex Savatieiev5118de02019-02-20 15:50:42 -06006from cfg_checker.common import const
Alex3ebc5632019-04-18 16:47:18 -05007from cfg_checker.common import logger_cli
Alex1839bbf2019-08-22 17:17:21 -05008from cfg_checker.common.file_utils import read_file_as_lines
Alex836fac82019-08-22 13:36:16 -05009from cfg_checker.nodes import salt_master
Alex3ebc5632019-04-18 16:47:18 -050010
11import jinja2
12
13import six
savex4448e132018-04-25 15:51:14 +020014
15pkg_dir = os.path.dirname(__file__)
Alex Savatieiev6d010be2019-03-11 10:36:59 -050016pkg_dir = os.path.join(pkg_dir, os.pardir, os.pardir)
savex4448e132018-04-25 15:51:14 +020017pkg_dir = os.path.normpath(pkg_dir)
18
Alex836fac82019-08-22 13:36:16 -050019# % threshhold values
20_disk_warn = 80
21_disk_critical = 90
22_ram_warn = 5
23_ram_critical = 3
Alex1839bbf2019-08-22 17:17:21 -050024_softnet_interval = 5
25
26UP = const.NODE_UP
27DOWN = const.NODE_DOWN
Alex836fac82019-08-22 13:36:16 -050028
savex4448e132018-04-25 15:51:14 +020029
savex4448e132018-04-25 15:51:14 +020030def line_breaks(text):
31 # replace python linebreaks with html breaks
32 return text.replace("\n", "<br />")
33
34
Alex41485522019-04-12 17:26:18 -050035def get_sorted_keys(td):
36 # detect if we can sort by desc
37 # Yes, this is slow, but bullet-proof from empty desc
38 _desc = all([bool(td[k]['desc']) for k in td.keys()])
39 # Get sorted list
40 if not _desc:
41 return sorted(td.keys())
42 else:
43 return sorted(
44 td.keys(),
45 key=lambda k: (
Alexd0391d42019-05-21 18:48:55 -050046 td[k]['desc']['section'],
Alex41485522019-04-12 17:26:18 -050047 td[k]['desc']['app'],
48 k
49 )
50 )
51
52
53def get_max(_list):
54 return sorted(_list)[-1]
55
56
Alex836fac82019-08-22 13:36:16 -050057def make_pkg_action_label(act):
Alex41485522019-04-12 17:26:18 -050058 _act_labels = {
59 const.ACT_UPGRADE: "Upgrade possible",
60 const.ACT_NEED_UP: "Needs upgrade",
61 const.ACT_NEED_DOWN: "Needs downgrade",
Alex9e4bfaf2019-06-11 15:21:59 -050062 const.ACT_REPO: "Repo update",
Alex41485522019-04-12 17:26:18 -050063 const.ACT_NA: ""
64 }
65 return _act_labels[act]
66
67
Alex836fac82019-08-22 13:36:16 -050068def make_pkg_action_class(act):
Alex41485522019-04-12 17:26:18 -050069 _act_classes = {
70 const.ACT_UPGRADE: "possible",
71 const.ACT_NEED_UP: "needs_up",
72 const.ACT_NEED_DOWN: "needs_down",
73 const.ACT_REPO: "needs_repo",
74 const.ACT_NA: ""
75 }
76 return _act_classes[act]
77
78
Alex836fac82019-08-22 13:36:16 -050079def make_pkg_status_label(sts):
Alex41485522019-04-12 17:26:18 -050080 _status_labels = {
81 const.VERSION_OK: "OK",
82 const.VERSION_UP: "Upgraded",
83 const.VERSION_DOWN: "Downgraded",
Alex26b8a8c2019-10-09 17:09:07 -050084 const.VERSION_WARN: "WARNING",
Alex41485522019-04-12 17:26:18 -050085 const.VERSION_ERR: "ERROR",
86 const.VERSION_NA: "N/A"
87 }
88 return _status_labels[sts]
89
90
Alex836fac82019-08-22 13:36:16 -050091def make_pkg_status_class(sts):
92 return const.all_pkg_statuses[sts]
93
94
95def make_node_status(sts):
96 return const.node_status[sts]
Alex41485522019-04-12 17:26:18 -050097
98
Alexd0391d42019-05-21 18:48:55 -050099def make_repo_info(repos):
100 _text = ""
101 for r in repos:
102 # tag
103 _text += r['tag'] + ": "
104 # repo header
105 _text += " ".join([
106 r['subset'],
107 r['release'],
108 r['ubuntu-release'],
109 r['type'],
110 r['arch']
111 ]) + ", "
112 # maintainer w/o email
113 _m = r['maintainer'][:r['maintainer'].find('<')-1]
114 _m_ascii = _m.encode('ascii', errors="xmlcharrefreplace")
115 _text += _m_ascii
116 # newline
117 _text += "<br />"
118 return _text
119
120
savex4448e132018-04-25 15:51:14 +0200121@six.add_metaclass(abc.ABCMeta)
122class _Base(object):
123 def __init__(self):
124 self.jinja2_env = self.init_jinja2_env()
125
126 @abc.abstractmethod
127 def __call__(self, payload):
128 pass
129
130 @staticmethod
131 def init_jinja2_env():
132 return jinja2.Environment(
133 loader=jinja2.FileSystemLoader(os.path.join(pkg_dir, 'templates')),
134 trim_blocks=True,
135 lstrip_blocks=True)
136
137
138class _TMPLBase(_Base):
139 @abc.abstractproperty
140 def tmpl(self):
141 pass
142
143 @staticmethod
144 def _count_totals(data):
145 data['counters']['total_nodes'] = len(data['nodes'])
146
Alex Savatieiev36b938d2019-01-21 11:01:18 +0100147 def __call__(self, payload):
savex4448e132018-04-25 15:51:14 +0200148 # init data structures
149 data = self.common_data()
Alex41485522019-04-12 17:26:18 -0500150 # payload should have pre-sorted structure according to report called
151 # nodes, openstack_release, mcp_release, etc...
152 data.update(payload)
savex4448e132018-04-25 15:51:14 +0200153
154 # add template specific data
155 self._extend_data(data)
156
157 # do counts global
158 self._count_totals(data)
159
160 # specific filters
savex4448e132018-04-25 15:51:14 +0200161 self.jinja2_env.filters['linebreaks'] = line_breaks
Alex41485522019-04-12 17:26:18 -0500162 self.jinja2_env.filters['get_max'] = get_max
163
164 self.jinja2_env.filters['get_sorted_keys'] = get_sorted_keys
Alex836fac82019-08-22 13:36:16 -0500165 self.jinja2_env.filters['pkg_status_label'] = make_pkg_status_label
166 self.jinja2_env.filters['pkg_status_class'] = make_pkg_status_class
167 self.jinja2_env.filters['pkg_action_label'] = make_pkg_action_label
168 self.jinja2_env.filters['pkg_action_class'] = make_pkg_action_class
169 self.jinja2_env.filters['node_status_class'] = make_node_status
Alexc6566d82019-09-23 16:07:17 -0500170 self.jinja2_env.filters['pkg_repo_info'] = make_repo_info
savex4448e132018-04-25 15:51:14 +0200171
172 # render!
Alex41485522019-04-12 17:26:18 -0500173 logger_cli.info("-> Using template: {}".format(self.tmpl))
savex4448e132018-04-25 15:51:14 +0200174 tmpl = self.jinja2_env.get_template(self.tmpl)
Alex41485522019-04-12 17:26:18 -0500175 logger_cli.info("-> Rendering")
savex4448e132018-04-25 15:51:14 +0200176 return tmpl.render(data)
177
178 def common_data(self):
179 return {
180 'counters': {},
Alex41485522019-04-12 17:26:18 -0500181 'salt_info': {},
182 'gen_date': time.strftime("%m/%d/%Y %H:%M:%S")
savex4448e132018-04-25 15:51:14 +0200183 }
184
185 def _extend_data(self, data):
186 pass
187
188
Alex41485522019-04-12 17:26:18 -0500189# HTML Package versions report
190class CSVAllPackages(_TMPLBase):
191 tmpl = "pkg_versions_csv.j2"
192
193
194# HTML Package versions report
savexce010ba2018-04-27 09:49:23 +0200195class HTMLPackageCandidates(_TMPLBase):
Alex41485522019-04-12 17:26:18 -0500196 tmpl = "pkg_versions_html.j2"
savex4448e132018-04-25 15:51:14 +0200197
198
Alex Savatieievd48994d2018-12-13 12:13:00 +0100199# Package versions report
200class HTMLModelCompare(_TMPLBase):
201 tmpl = "model_tree_cmp_tmpl.j2"
202
203 def _extend_data(self, data):
Alex Savatieiev36b938d2019-01-21 11:01:18 +0100204 # move names into separate place
Alexb8af13a2019-04-16 18:38:12 -0500205 data["names"] = data["diffs"].pop("diff_names")
206 data["tabs"] = data.pop("diffs")
Alex3ebc5632019-04-18 16:47:18 -0500207
Alex Savatieievd48994d2018-12-13 12:13:00 +0100208 # counters - mdl_diff
Alex Savatieiev4f149d02019-02-28 17:15:29 -0600209 for _tab in data["tabs"].keys():
210 data['counters'][_tab] = len(data["tabs"][_tab]["diffs"].keys())
Alex Savatieievd48994d2018-12-13 12:13:00 +0100211
212
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600213class HTMLNetworkReport(_TMPLBase):
214 tmpl = "network_check_tmpl.j2"
215
Alex836fac82019-08-22 13:36:16 -0500216 def _extend_data(self, data):
217 def get_bytes(value):
218 if value[-1] == 'G':
219 return int(float(value[:-1]) * 1024 * 1024 * 1024)
220 elif value[-1] == 'M':
221 return int(float(value[:-1]) * 1024 * 1024)
222 elif value[-1] == 'K':
223 return int(float(value[:-1]) * 1024)
224 else:
225 return int(value)
226
Alex1839bbf2019-08-22 17:17:21 -0500227 def _lscpu(_dict):
228 _key = "lscpu"
229 _key_r = "lscpu_raw"
230 # get all of the values
Alex836fac82019-08-22 13:36:16 -0500231 _f_cmd = salt_master.get_cmd_for_nodes
Alex1839bbf2019-08-22 17:17:21 -0500232 _cmd = "lscpu | sed -n '/\\:/s/ \\+/ /gp'"
233 _f_cmd(_cmd, _key_r, target_dict=_dict)
234 # parse them and put into dict
235 for node, dt in _dict.iteritems():
236 dt[_key] = {}
237 if dt['status'] == DOWN:
Alexe65ff4e2019-10-11 14:45:09 -0500238 dt.pop(_key_r)
239 continue
240 if not dt[_key_r]:
241 # no stats collected, put negatives
242 dt.pop(_key_r)
243 dt[_key] = {}
Alex1839bbf2019-08-22 17:17:21 -0500244 continue
245 lines = dt[_key_r].splitlines()
246 for line in lines:
247 li = line.split(':')
248 _var_name = li[0].lower()
249 _var_name = re.sub(' ', '_', _var_name)
250 _var_name = re.sub('|'.join(['\\(', '\\)']), '', _var_name)
251 _var_value = li[1].strip()
252 dt[_key][_var_name] = _var_value
253 dt.pop(_key_r)
254 # detect virtual nodes
255 if "hypervisor_vendor" in dt[_key]:
256 dt['node_type'] = "virtual"
257 else:
258 dt['node_type'] = "physical"
Alex836fac82019-08-22 13:36:16 -0500259
Alex1839bbf2019-08-22 17:17:21 -0500260 def _free(_dict):
261 _key = "ram"
262 _key_r = "ram_raw"
Alex836fac82019-08-22 13:36:16 -0500263 _f_cmd = salt_master.get_cmd_for_nodes
Alex1839bbf2019-08-22 17:17:21 -0500264 _cmd = "free -h | sed -n '/Mem/s/ \\+/ /gp'"
265 _f_cmd(_cmd, _key_r, target_dict=_dict)
266 # parse them and put into dict
267 for node, dt in _dict.iteritems():
268 dt[_key] = {}
269 if dt['status'] == DOWN:
Alexe65ff4e2019-10-11 14:45:09 -0500270 dt.pop(_key_r)
271 continue
272 if not dt[_key_r]:
273 # no stats collected, put negatives
274 dt.pop(_key_r)
275 dt[_key] = {}
Alex1839bbf2019-08-22 17:17:21 -0500276 continue
277 li = dt[_key_r].split()
278 dt[_key]['total'] = li[1]
279 dt[_key]['used'] = li[2]
280 dt[_key]['free'] = li[3]
281 dt[_key]['shared'] = li[4]
282 dt[_key]['cache'] = li[5]
283 dt[_key]['available'] = li[6]
284
285 _total = get_bytes(li[1])
286 _avail = get_bytes(li[6])
287 _m = _avail * 100.0 / _total
288 if _m < _ram_critical:
289 dt[_key]["status"] = "fail"
290 elif _m < _ram_warn:
291 dt[_key]["status"] = "warn"
292 else:
293 dt[_key]["status"] = ""
Alex836fac82019-08-22 13:36:16 -0500294
295 def _services(_dict):
296 _key = "services"
297 _key_r = "services_raw"
298 _f_cmd = salt_master.get_cmd_for_nodes
299 _cmd = "service --status-all"
300 _f_cmd(_cmd, _key_r, target_dict=_dict)
301 for node, dt in _dict.iteritems():
302 dt[_key] = {}
Alex1839bbf2019-08-22 17:17:21 -0500303 if dt['status'] == DOWN:
Alexe65ff4e2019-10-11 14:45:09 -0500304 dt.pop(_key_r)
305 continue
306 if not dt[_key_r]:
307 # no stats collected, put negatives
308 dt.pop(_key_r)
309 dt[_key] = {}
Alex1839bbf2019-08-22 17:17:21 -0500310 continue
Alex836fac82019-08-22 13:36:16 -0500311 lines = dt[_key_r].splitlines()
312 for line in lines:
313 li = line.split()
314 _status = li[1]
315 _name = li[3]
316 if _status == '-':
317 dt[_key][_name] = False
318 elif _status == '+':
319 dt[_key][_name] = True
320 else:
321 dt[_key][_name] = None
322 dt.pop(_key_r)
323
Alex1839bbf2019-08-22 17:17:21 -0500324 def _vcp_status(_dict):
325 _key = "virsh"
326 _key_r = "virsh_raw"
327 salt_master.get_cmd_for_nodes(
328 "virsh list --all | sed -n -e '/[0-9]/s/ \\+/ /gp'",
329 _key_r,
330 target_dict=_dict,
331 nodes="kvm*"
332 )
333 _kvm = filter(lambda x: x.find("kvm") >= 0, _dict.keys())
334 for node in _kvm:
335 dt = _dict[node]
336 dt[_key] = {}
337 if dt['status'] == DOWN:
Alexe65ff4e2019-10-11 14:45:09 -0500338 dt.pop(_key_r)
339 continue
340 if not dt[_key_r]:
341 # no stats collected, put negatives
342 dt.pop(_key_r)
343 dt[_key] = {}
Alex1839bbf2019-08-22 17:17:21 -0500344 continue
345 lines = dt[_key_r].splitlines()
346 for line in lines:
347 li = line.split()
348 _id = li[0]
349 _name = li[1]
350 _status = li[2]
351 dt[_key][_name] = {
352 'id': _id,
353 'status': _status
354 }
355 dt.pop(_key_r)
356
357 # query per-cpu and count totals
358 # total (0), dropped(1), squeezed (2), collision (7)
359 def _soft_net_stats(_dict):
360 _key = "net_stats"
361 _key_r = "net_stats_raw"
362 _f_cmd = salt_master.get_cmd_for_nodes
363 _cmd = "cat /proc/net/softnet_stat; echo \\#; " \
364 "sleep {}; cat /proc/net/softnet_stat".format(
365 _softnet_interval
366 )
367 _f_cmd(_cmd, _key_r, target_dict=_dict)
368 for node, dt in _dict.iteritems():
369 _cpuindex = 1
370 _add_mode = True
Alex1839bbf2019-08-22 17:17:21 -0500371 # totals for start mark
372 _ts = [0, 0, 0, 0]
373 # skip if node is down
374 if dt['status'] == DOWN:
Alexf3dbe862019-10-07 15:17:04 -0500375 dt.pop(_key_r)
Alex1839bbf2019-08-22 17:17:21 -0500376 continue
Alexf3dbe862019-10-07 15:17:04 -0500377 if not dt[_key_r]:
378 # no stats collected, put negatives
379 dt.pop(_key_r)
380 dt[_key] = {
381 "total": [-1, -1, -1, -1]
382 }
383 continue
384 # final totals
385 dt[_key] = {
386 "total": [0, 0, 0, 0]
387 }
Alex1839bbf2019-08-22 17:17:21 -0500388 lines = dt[_key_r].splitlines()
389 for line in lines:
390 if line.startswith("#"):
391 _add_mode = False
392 _cpuindex = 1
393 continue
394 li = line.split()
395 _c = [
396 int(li[0], 16),
397 int(li[1], 16),
398 int(li[2], 16),
399 int(li[7], 16)
400 ]
401 _id = "cpu{:02}".format(_cpuindex)
402 if _id not in dt[_key]:
403 dt[_key][_id] = []
404 _dc = dt[_key][_id]
405 if _add_mode:
406 # saving values and adding totals
407 dt[_key][_id] = _c
408 # save start totals
409 _ts = [_ts[i]+_c[i] for i in range(0, len(_c))]
410 else:
411 # this is second measurement
412 # subtract all values
413 for i in range(len(_c)):
414 dt[_key][_id][i] = _c[i] - _dc[i]
415 dt[_key]["total"][i] += _c[i]
416 _cpuindex += 1
417 # finally, subtract initial totals
418 for k, v in dt[_key].iteritems():
419 if k != "total":
420 dt[_key][k] = [v[i] / 5. for i in range(len(v))]
421 else:
422 dt[_key][k] = [(v[i]-_ts[i])/5. for i in range(len(v))]
423 dt.pop(_key_r)
424
425 # prepare yellow and red marker values
Alex836fac82019-08-22 13:36:16 -0500426 data["const"] = {
Alex1839bbf2019-08-22 17:17:21 -0500427 "net_interval": _softnet_interval,
Alex836fac82019-08-22 13:36:16 -0500428 "ram_warn": _ram_warn,
429 "ram_critical": _ram_critical,
430 "disk_warn": _disk_warn,
Alex1839bbf2019-08-22 17:17:21 -0500431 "disk_critical": _disk_critical,
432 "services": read_file_as_lines(
433 os.path.join(
434 pkg_dir,
435 'etc',
436 'services.list'
437 )
438 )
Alex836fac82019-08-22 13:36:16 -0500439 }
440
441 # get kernel version
442 salt_master.get_cmd_for_nodes(
443 "uname -r",
444 "kernel",
445 target_dict=data["nodes"]
446 )
Alex1839bbf2019-08-22 17:17:21 -0500447 # process lscpu data
448 _lscpu(data["nodes"])
Alex836fac82019-08-22 13:36:16 -0500449
450 # free ram
451 # sample: 16425392 14883144 220196
Alex1839bbf2019-08-22 17:17:21 -0500452 _free(data["nodes"])
Alex836fac82019-08-22 13:36:16 -0500453
454 # disk space
455 # sample: /dev/vda1 78G 33G 45G 43%
Alexe65ff4e2019-10-11 14:45:09 -0500456 _key = "disk"
457 _key_r = "disk_raw"
Alex836fac82019-08-22 13:36:16 -0500458 salt_master.get_cmd_for_nodes(
459 "df -h | sed -n '/^\\/dev/s/ \\+/ /gp' | cut -d\" \" -f 1-5",
460 "disk_raw",
461 target_dict=data["nodes"]
462 )
Alexe65ff4e2019-10-11 14:45:09 -0500463 for dt in data["nodes"].itervalues():
464 if dt['status'] == DOWN:
465 dt.pop(_key_r)
466 continue
467 if not dt[_key_r]:
468 # no stats collected, put negatives
469 dt.pop(_key_r)
470 dt[_key] = {}
471 continue
472 dt["disk"] = {}
Alex836fac82019-08-22 13:36:16 -0500473 # show first device row by default
Alexe65ff4e2019-10-11 14:45:09 -0500474 dt["disk_max_dev"] = None
475 _d = dt["disk"]
476 _r = dt["disk_raw"]
Alex836fac82019-08-22 13:36:16 -0500477 _r = _r.splitlines()
478 _max = -1
479 for idx in range(0, len(_r)):
480 _t = _r[idx].split()
481 _d[_t[0]] = {}
482 _d[_t[0]]['v'] = _t[1:]
483 _chk = int(_t[-1].split('%')[0])
484 if _chk > _max:
Alexe65ff4e2019-10-11 14:45:09 -0500485 dt["disk_max_dev"] = _t[0]
Alex836fac82019-08-22 13:36:16 -0500486 _max = _chk
487 if _chk > _disk_critical:
488 _d[_t[0]]['f'] = "fail"
489 elif _chk > _disk_warn:
490 _d[_t[0]]['f'] = "warn"
491 else:
492 _d[_t[0]]['f'] = ""
493
494 # prepare networks data for report
495 for net, net_v in data['map'].iteritems():
496 for node, ifs in net_v.iteritems():
497 for d in ifs:
498 _err = "fail"
499 d['interface_error'] = _err if d['interface_error'] else ""
500 d['mtu_error'] = _err if d['mtu_error'] else ""
501 d['status_error'] = _err if d['status_error'] else ""
502 d['subnet_gateway_error'] = \
503 _err if d['subnet_gateway_error'] else ""
504
505 _services(data["nodes"])
Alex1839bbf2019-08-22 17:17:21 -0500506 # vcp status
507 # query virsh and prepare for report
508 _vcp_status(data["nodes"])
509
510 # soft net stats
511 _soft_net_stats(data["nodes"])
Alex836fac82019-08-22 13:36:16 -0500512
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600513
savex4448e132018-04-25 15:51:14 +0200514class ReportToFile(object):
515 def __init__(self, report, target):
516 self.report = report
517 self.target = target
518
519 def __call__(self, payload):
520 payload = self.report(payload)
521
522 if isinstance(self.target, six.string_types):
523 self._wrapped_dump(payload)
524 else:
525 self._dump(payload, self.target)
526
527 def _wrapped_dump(self, payload):
528 with open(self.target, 'wt') as target:
529 self._dump(payload, target)
530
531 @staticmethod
532 def _dump(payload, target):
533 target.write(payload)