Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 1 | import functools |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 2 | import os |
| 3 | import re |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 4 | import subprocess |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 5 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 6 | from cfg_checker.common import logger_cli |
| 7 | from cfg_checker.common.const import all_salt_roles_map, uknown_code, \ |
| 8 | truth |
Alex Savatieiev | 5118de0 | 2019-02-20 15:50:42 -0600 | [diff] [blame] | 9 | from cfg_checker.common.exception import ConfigException |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 10 | |
Alex Savatieiev | 5118de0 | 2019-02-20 15:50:42 -0600 | [diff] [blame] | 11 | pkg_dir = os.path.dirname(__file__) |
| 12 | pkg_dir = os.path.join(pkg_dir, os.pardir, os.pardir) |
| 13 | pkg_dir = os.path.normpath(pkg_dir) |
| 14 | pkg_dir = os.path.abspath(pkg_dir) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 15 | |
| 16 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 17 | # 'Dirty' and simple way to execute piped cmds |
Alex | b78191f | 2021-11-02 16:35:46 -0500 | [diff] [blame] | 18 | def piped_shell(command, code=False): |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 19 | logger_cli.debug("... cmd:'{}'".format(command)) |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 20 | _code, _out = subprocess.getstatusoutput(command) |
| 21 | if _code: |
| 22 | logger_cli.error("Non-zero return code: {}, '{}'".format(_code, _out)) |
Alex | b78191f | 2021-11-02 16:35:46 -0500 | [diff] [blame] | 23 | if code: |
| 24 | return _code, _out |
| 25 | else: |
| 26 | return _out |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 27 | |
| 28 | |
| 29 | # 'Proper way to execute shell |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 30 | def shell(command): |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 31 | logger_cli.debug("... cmd:'{}'".format(command)) |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 32 | _ps = subprocess.Popen( |
| 33 | command.split(), |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 34 | stdout=subprocess.PIPE, |
| 35 | universal_newlines=False |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 36 | ).communicate()[0].decode() |
| 37 | |
| 38 | return _ps |
| 39 | |
| 40 | |
Alex | 26b8a8c | 2019-10-09 17:09:07 -0500 | [diff] [blame] | 41 | def merge_dict(source, destination): |
| 42 | """ |
| 43 | Dict merger, thanks to vincent |
| 44 | http://stackoverflow.com/questions/20656135/python-deep-merge-dictionary-data |
| 45 | |
| 46 | >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } } |
| 47 | >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } } |
| 48 | >>> merge(b, a) == { |
| 49 | 'first': { |
| 50 | 'all_rows': { |
| 51 | 'pass': 'dog', |
| 52 | 'fail': 'cat', |
| 53 | 'number': '5' |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | True |
| 58 | """ |
| 59 | for key, value in source.items(): |
| 60 | if isinstance(value, dict): |
| 61 | # get node or create one |
| 62 | node = destination.setdefault(key, {}) |
| 63 | merge_dict(value, node) |
| 64 | else: |
| 65 | destination[key] = value |
| 66 | |
| 67 | return destination |
| 68 | |
| 69 | |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 70 | class Utils(object): |
| 71 | @staticmethod |
| 72 | def validate_name(fqdn, message=False): |
| 73 | """ |
| 74 | Function that tries to validate node name. |
| 75 | Checks if code contains letters, has '.' in it, |
| 76 | roles map contains code's role |
| 77 | |
| 78 | :param fqdn: node FQDN name to supply for the check |
| 79 | :param message: True if validate should return error check message |
| 80 | :return: False if checks failed, True if all checks passed |
| 81 | """ |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 82 | _message = "# Validation passed" |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 83 | |
| 84 | def _result(): |
| 85 | return (True, _message) if message else True |
| 86 | |
| 87 | # node role code checks |
Alex | d0391d4 | 2019-05-21 18:48:55 -0500 | [diff] [blame] | 88 | _code = re.findall(r"[a-zA-Z]+", fqdn.split('.')[0]) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 89 | if len(_code) > 0: |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 90 | if _code[0] in all_salt_roles_map: |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 91 | return _result() |
| 92 | else: |
| 93 | # log warning here |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 94 | _message = "# Node code is unknown, '{}'. " \ |
| 95 | "# Please, update map".format(_code) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 96 | else: |
| 97 | # log warning here |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 98 | _message = "# Node name is invalid, '{}'".format(fqdn) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 99 | |
| 100 | # put other checks here |
| 101 | |
| 102 | # output result |
| 103 | return _result() |
| 104 | |
| 105 | @staticmethod |
| 106 | def node_string_to_list(node_string): |
| 107 | # supplied var should contain node list |
| 108 | # if there is no ',' -> use space as a delimiter |
| 109 | if node_string is not None: |
| 110 | if node_string.find(',') < 0: |
| 111 | return node_string.split(' ') |
| 112 | else: |
| 113 | return node_string.split(',') |
| 114 | else: |
| 115 | return [] |
| 116 | |
| 117 | def get_node_code(self, fqdn): |
| 118 | # validate |
| 119 | _isvalid, _message = self.validate_name(fqdn, message=True) |
Alex | 2e213b2 | 2019-12-05 10:40:29 -0600 | [diff] [blame] | 120 | _code = re.findall( |
| 121 | r"[a-zA-Z]+?(?=(?:[0-9]+$)|(?:\-+?)|(?:\_+?)|$)", |
| 122 | fqdn.split('.')[0] |
| 123 | ) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 124 | # check if it is valid and raise if not |
| 125 | if _isvalid: |
Alex | e0c5b9e | 2019-04-23 18:51:23 -0500 | [diff] [blame] | 126 | # try to match it with ones in map |
| 127 | _c = _code[0] |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 128 | match = any([r in _c for r in all_salt_roles_map.keys()]) |
Alex | e0c5b9e | 2019-04-23 18:51:23 -0500 | [diff] [blame] | 129 | if match: |
| 130 | # no match, try to find it |
| 131 | match = False |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 132 | for r in all_salt_roles_map.keys(): |
Alex | e0c5b9e | 2019-04-23 18:51:23 -0500 | [diff] [blame] | 133 | _idx = _c.find(r) |
| 134 | if _idx > -1: |
| 135 | _c = _c[_idx:] |
| 136 | match = True |
| 137 | break |
| 138 | if match: |
| 139 | return _c |
| 140 | else: |
| 141 | return uknown_code |
| 142 | else: |
| 143 | return uknown_code |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 144 | else: |
| 145 | raise ConfigException(_message) |
| 146 | |
Alex | e9908f7 | 2020-05-19 16:04:53 -0500 | [diff] [blame] | 147 | def get_nodes_list(self, nodes_list, env_sting=None): |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 148 | _list = [] |
Alex | e9908f7 | 2020-05-19 16:04:53 -0500 | [diff] [blame] | 149 | if env_sting is None: |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 150 | # nothing supplied, use the one in repo |
| 151 | try: |
Alex Savatieiev | d48994d | 2018-12-13 12:13:00 +0100 | [diff] [blame] | 152 | if not nodes_list: |
| 153 | return [] |
Alex | e9908f7 | 2020-05-19 16:04:53 -0500 | [diff] [blame] | 154 | with open(nodes_list) as _f: |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 155 | _list.extend(_f.read().splitlines()) |
| 156 | except IOError as e: |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 157 | raise ConfigException("# Error while loading file, '{}': " |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 158 | "{}".format(e.filename, e.strerror)) |
| 159 | else: |
Alex | e9908f7 | 2020-05-19 16:04:53 -0500 | [diff] [blame] | 160 | _list.extend(self.node_string_to_list(env_sting)) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 161 | |
| 162 | # validate names |
| 163 | _invalid = [] |
| 164 | _valid = [] |
| 165 | for idx in range(len(_list)): |
| 166 | _name = _list[idx] |
| 167 | if not self.validate_name(_name): |
| 168 | _invalid.append(_name) |
| 169 | else: |
| 170 | _valid.append(_name) |
| 171 | |
Alex | e9908f7 | 2020-05-19 16:04:53 -0500 | [diff] [blame] | 172 | return _valid, _invalid |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 173 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 174 | @staticmethod |
| 175 | def to_bool(value): |
| 176 | if value.lower() in truth: |
| 177 | return True |
| 178 | else: |
| 179 | return False |
| 180 | |
| 181 | # helper functions to get nested attrs |
| 182 | # https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-subobjects-chained-properties |
| 183 | # using wonder's beautiful simplification: |
| 184 | # https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects/31174427?noredirect=1#comment86638618_31174427 |
| 185 | def rsetattr(self, obj, attr, val): |
| 186 | pre, _, post = attr.rpartition('.') |
| 187 | return setattr(self.rgetattr(obj, pre) if pre else obj, post, val) |
| 188 | |
| 189 | def rgetattr(self, obj, attr, *args): |
| 190 | def _getattr(obj, attr): |
| 191 | return getattr(obj, attr, *args) |
| 192 | return functools.reduce(_getattr, [obj] + attr.split('.')) |
| 193 | |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 194 | |
| 195 | utils = Utils() |