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