blob: 809a9c0a67cb0b4ec6086525ca86617051a416fc [file] [log] [blame]
savex4448e132018-04-25 15:51:14 +02001import os
2import re
3
4from check_versions.common.const import all_roles_map
5
6from check_versions.common.exception import ConfigException
7
8PKG_DIR = os.path.dirname(__file__)
9PKG_DIR = os.path.join(PKG_DIR, os.pardir, os.pardir)
10PKG_DIR = os.path.normpath(PKG_DIR)
11
12
13class Utils(object):
14 @staticmethod
15 def validate_name(fqdn, message=False):
16 """
17 Function that tries to validate node name.
18 Checks if code contains letters, has '.' in it,
19 roles map contains code's role
20
21 :param fqdn: node FQDN name to supply for the check
22 :param message: True if validate should return error check message
23 :return: False if checks failed, True if all checks passed
24 """
25 _message = "Validation passed"
26
27 def _result():
28 return (True, _message) if message else True
29
30 # node role code checks
31 _code = re.findall("[a-zA-Z]+", fqdn.split('.')[0])
32 if len(_code) > 0:
33 if _code[0] in all_roles_map:
34 return _result()
35 else:
36 # log warning here
37 _message = "Node code is unknown, '{}'. " \
38 "Please, update map".format(_code)
39 else:
40 # log warning here
41 _message = "Node name is invalid, '{}'".format(fqdn)
42
43 # put other checks here
44
45 # output result
46 return _result()
47
48 @staticmethod
49 def node_string_to_list(node_string):
50 # supplied var should contain node list
51 # if there is no ',' -> use space as a delimiter
52 if node_string is not None:
53 if node_string.find(',') < 0:
54 return node_string.split(' ')
55 else:
56 return node_string.split(',')
57 else:
58 return []
59
60 def get_node_code(self, fqdn):
61 # validate
62 _isvalid, _message = self.validate_name(fqdn, message=True)
63 _code = re.findall("[a-zA-Z]+", fqdn.split('.')[0])
64 # check if it is valid and raise if not
65 if _isvalid:
66 return _code[0]
67 else:
68 raise ConfigException(_message)
69
70 def get_nodes_list(self, env):
71 _list = []
72 if env is None:
73 # nothing supplied, use the one in repo
74 try:
75 with open(os.path.join(PKG_DIR, 'etc', 'nodes.list')) as _f:
76 _list.extend(_f.read().splitlines())
77 except IOError as e:
78 raise ConfigException("Error while loading file, '{}': "
79 "{}".format(e.filename, e.strerror))
80 else:
81 _list.extend(self.node_string_to_list(env))
82
83 # validate names
84 _invalid = []
85 _valid = []
86 for idx in range(len(_list)):
87 _name = _list[idx]
88 if not self.validate_name(_name):
89 _invalid.append(_name)
90 else:
91 _valid.append(_name)
92
93 return _valid
94
95
96utils = Utils()