blob: ca4e2619e8c3001e9d616681a0836ebdad2b14b7 [file] [log] [blame]
Alexe0c5b9e2019-04-23 18:51:23 -05001import json
Alex Savatieiev9b2f6512019-02-20 18:05:00 -06002import os
Alex3ebc5632019-04-18 16:47:18 -05003from copy import deepcopy
Alex Savatieiev9b2f6512019-02-20 18:05:00 -06004
Alexe0c5b9e2019-04-23 18:51:23 -05005from cfg_checker.clients import get_salt_remote, salt
Alex3ebc5632019-04-18 16:47:18 -05006from cfg_checker.common import config, const
Alex7c9494e2019-04-22 10:40:59 -05007from cfg_checker.common import logger, logger_cli
Alexe0c5b9e2019-04-23 18:51:23 -05008from cfg_checker.common import utils
9from cfg_checker.common.exception import SaltException
Alex7c9494e2019-04-22 10:40:59 -050010from cfg_checker.common.settings import pkg_dir
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060011
12node_tmpl = {
13 'role': '',
14 'node_group': '',
15 'status': const.NODE_DOWN,
16 'pillars': {},
17 'grains': {}
18}
19
20
21class SaltNodes(object):
22 def __init__(self):
Alexe0c5b9e2019-04-23 18:51:23 -050023 logger_cli.info("# Gathering environment information")
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060024 # simple salt rest client
Alexe0c5b9e2019-04-23 18:51:23 -050025 self.salt = salt
26 self.nodes = None
Alex3ebc5632019-04-18 16:47:18 -050027
Alexe0c5b9e2019-04-23 18:51:23 -050028 def gather_node_info(self):
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060029 # Keys for all nodes
30 # this is not working in scope of 2016.8.3, will overide with list
Alexb151fbe2019-04-22 16:53:30 -050031 logger_cli.debug("... collecting node names existing in the cloud")
Alexe0c5b9e2019-04-23 18:51:23 -050032 if not self.salt:
33 self.salt = get_salt_remote(config)
34
Alex Savatieiev9df93a92019-02-27 17:40:16 -060035 try:
36 _keys = self.salt.list_keys()
37 _str = []
38 for _k, _v in _keys.iteritems():
39 _str.append("{}: {}".format(_k, len(_v)))
40 logger_cli.info("-> keys collected: {}".format(", ".join(_str)))
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060041
Alex Savatieiev9df93a92019-02-27 17:40:16 -060042 self.node_keys = {
43 'minions': _keys['minions']
44 }
Alex3ebc5632019-04-18 16:47:18 -050045 except Exception:
Alex Savatieiev9df93a92019-02-27 17:40:16 -060046 _keys = None
47 self.node_keys = None
Alex3ebc5632019-04-18 16:47:18 -050048
Alex Savatieiev9df93a92019-02-27 17:40:16 -060049 # List of minions with grains
50 _minions = self.salt.list_minions()
51 if _minions:
Alex3ebc5632019-04-18 16:47:18 -050052 logger_cli.info(
53 "-> api reported {} active minions".format(len(_minions))
54 )
Alex Savatieiev9df93a92019-02-27 17:40:16 -060055 elif not self.node_keys:
56 # this is the last resort
57 _minions = config.load_nodes_list()
Alex3ebc5632019-04-18 16:47:18 -050058 logger_cli.info(
59 "-> {} nodes loaded from list file".format(len(_minions))
60 )
Alex Savatieiev9df93a92019-02-27 17:40:16 -060061 else:
62 _minions = self.node_keys['minions']
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060063
Alex Savatieiev9df93a92019-02-27 17:40:16 -060064 # in case API not listed minions, we need all that answer ping
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060065 _active = self.salt.get_active_nodes()
Alex Savatieiev9df93a92019-02-27 17:40:16 -060066 logger_cli.info("-> nodes responded: {}".format(len(_active)))
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060067 # iterate through all accepted nodes and create a dict for it
68 self.nodes = {}
Alex Savatieievefa79c42019-03-14 19:14:04 -050069 self.skip_list = []
Alex Savatieiev9df93a92019-02-27 17:40:16 -060070 for _name in _minions:
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060071 _nc = utils.get_node_code(_name)
72 _rmap = const.all_roles_map
73 _role = _rmap[_nc] if _nc in _rmap else 'unknown'
74 _status = const.NODE_UP if _name in _active else const.NODE_DOWN
Alex Savatieievefa79c42019-03-14 19:14:04 -050075 if _status == const.NODE_DOWN:
76 self.skip_list.append(_name)
77 logger_cli.info("-> '{}' is down, marked to skip".format(
78 _name
79 ))
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060080 self.nodes[_name] = deepcopy(node_tmpl)
81 self.nodes[_name]['node_group'] = _nc
82 self.nodes[_name]['role'] = _role
83 self.nodes[_name]['status'] = _status
Alex Savatieievefa79c42019-03-14 19:14:04 -050084 logger_cli.info("-> {} nodes inactive".format(len(self.skip_list)))
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060085 logger_cli.info("-> {} nodes collected".format(len(self.nodes)))
86
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060087 # form an all nodes compound string to use in salt
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -060088 self.active_nodes_compound = self.salt.compound_string_from_list(
Alex Savatieiev9b2f6512019-02-20 18:05:00 -060089 filter(
90 lambda nd: self.nodes[nd]['status'] == const.NODE_UP,
91 self.nodes
92 )
93 )
Alex41485522019-04-12 17:26:18 -050094 # get master node fqdn
Alexe0c5b9e2019-04-23 18:51:23 -050095 _filtered = filter(
Alex41485522019-04-12 17:26:18 -050096 lambda nd: self.nodes[nd]['role'] == const.all_roles_map['cfg'],
97 self.nodes
Alexe0c5b9e2019-04-23 18:51:23 -050098 )
99 if len(_filtered) < 1:
100 raise SaltException(
101 "No master node detected! Check/Update node role map."
102 )
103 else:
104 self.salt.master_node = _filtered[0]
Alex3ebc5632019-04-18 16:47:18 -0500105
Alex41485522019-04-12 17:26:18 -0500106 # OpenStack versions
107 self.mcp_release = self.salt.pillar_get(
Alexe0c5b9e2019-04-23 18:51:23 -0500108 self.salt.master_node,
Alex41485522019-04-12 17:26:18 -0500109 "_param:apt_mk_version"
Alexe0c5b9e2019-04-23 18:51:23 -0500110 )[self.salt.master_node]
Alex41485522019-04-12 17:26:18 -0500111 self.openstack_release = self.salt.pillar_get(
Alexe0c5b9e2019-04-23 18:51:23 -0500112 self.salt.master_node,
Alex41485522019-04-12 17:26:18 -0500113 "_param:openstack_version"
Alexe0c5b9e2019-04-23 18:51:23 -0500114 )[self.salt.master_node]
Alexd0391d42019-05-21 18:48:55 -0500115 # Preload codenames
116 # do additional queries to get linux codename and arch for each node
117 self.get_specific_pillar_for_nodes("_param:linux_system_codename")
118 self.get_specific_pillar_for_nodes("_param:linux_system_architecture")
119 for _name in self.nodes.keys():
Alexe9547d82019-06-03 15:22:50 -0500120 _n = self.nodes[_name]
121 if _name not in self.skip_list:
122 _p = _n['pillars']['_param']
123 _n['linux_codename'] = _p['linux_system_codename']
124 _n['linux_arch'] = _p['linux_system_architecture']
Alex41485522019-04-12 17:26:18 -0500125
Alex Savatieieva1f6f8c2019-03-18 17:13:55 -0500126 def skip_node(self, node):
127 # Add node to skip list
128 # Fro example if it is fails to comply with the rules
129
130 # check if we know such node
131 if node in self.nodes.keys() and node not in self.skip_list:
132 # yes, add it
133 self.skip_list.append(node)
134 return True
135 else:
136 return False
137
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600138 def get_nodes(self):
Alexe0c5b9e2019-04-23 18:51:23 -0500139 if not self.nodes:
140 self.gather_node_info()
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600141 return self.nodes
142
Alex836fac82019-08-22 13:36:16 -0500143 def get_info(self):
144 _info = {
145 'mcp_release': self.mcp_release,
146 'openstack_release': self.openstack_release
147 }
148 return _info
149
150 def get_cmd_for_nodes(self, cmd, target_key, target_dict=None):
151 """Function runs. cmd.run and parses result into place
152 or into dict structure provided
153
154 :return: no return value, data pulished internally
155 """
156 logger_cli.debug(
157 "... collecting results for '{}'".format(cmd)
158 )
159 if target_dict:
160 _nodes = target_dict
161 else:
162 _nodes = self.nodes
163 _result = self.execute_cmd_on_active_nodes(cmd)
164 for node, data in _nodes.iteritems():
165 if node in self.skip_list:
166 logger_cli.debug(
167 "... '{}' skipped while collecting '{}'".format(
168 node,
169 cmd
170 )
171 )
172 continue
173 # Prepare target key
174 if target_key not in data:
175 data[target_key] = None
176 # Save data
177 if data['status'] == const.NODE_DOWN:
178 data[target_key] = None
179 elif not _result[node]:
180 logger_cli.debug(
181 "... '{}' not responded after '{}'".format(
182 node,
183 config.salt_timeout
184 )
185 )
186 data[target_key] = None
187 else:
188 data[target_key] = _result[node]
189
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600190 def get_specific_pillar_for_nodes(self, pillar_path):
191 """Function gets pillars on given path for all nodes
192
193 :return: no return value, data pulished internally
194 """
Alex3ebc5632019-04-18 16:47:18 -0500195 logger_cli.debug(
Alexb151fbe2019-04-22 16:53:30 -0500196 "... collecting node pillars for '{}'".format(pillar_path)
Alex3ebc5632019-04-18 16:47:18 -0500197 )
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600198 _result = self.salt.pillar_get(self.active_nodes_compound, pillar_path)
Alex Savatieievefa79c42019-03-14 19:14:04 -0500199 self.not_responded = []
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600200 for node, data in self.nodes.iteritems():
Alex Savatieievefa79c42019-03-14 19:14:04 -0500201 if node in self.skip_list:
202 logger_cli.debug(
203 "... '{}' skipped while collecting '{}'".format(
204 node,
205 pillar_path
206 )
207 )
208 continue
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600209 _pillar_keys = pillar_path.split(':')
210 _data = data['pillars']
211 # pre-create nested dict
212 for idx in range(0, len(_pillar_keys)-1):
213 _key = _pillar_keys[idx]
214 if _key not in _data:
215 _data[_key] = {}
216 _data = _data[_key]
Alex Savatieievefa79c42019-03-14 19:14:04 -0500217 if data['status'] == const.NODE_DOWN:
218 _data[_pillar_keys[-1]] = None
219 elif not _result[node]:
220 logger_cli.debug(
221 "... '{}' not responded after '{}'".format(
222 node,
223 config.salt_timeout
224 )
225 )
226 _data[_pillar_keys[-1]] = None
227 self.not_responded.append(node)
228 else:
229 _data[_pillar_keys[-1]] = _result[node]
Alex3ebc5632019-04-18 16:47:18 -0500230
Alexe0c5b9e2019-04-23 18:51:23 -0500231 def prepare_json_on_node(self, node, _dict, filename):
232 # this function assumes that all folders are created
233 _dumps = json.dumps(_dict, indent=2).splitlines()
234 _storage_path = os.path.join(
235 config.salt_file_root, config.salt_scripts_folder
236 )
237 logger_cli.debug(
238 "... uploading data as '{}' "
239 "to master's file cache folder: '{}'".format(
240 filename,
241 _storage_path
242 )
243 )
244 _cache_path = os.path.join(_storage_path, filename)
245 _source_path = os.path.join(
246 'salt://',
247 config.salt_scripts_folder,
248 filename
249 )
250 _target_path = os.path.join(
251 '/root',
252 config.salt_scripts_folder,
253 filename
254 )
255
256 logger_cli.debug("... creating file in cache '{}'".format(_cache_path))
257 self.salt.f_touch_master(_cache_path)
258 self.salt.f_append_master(_cache_path, _dumps)
259 logger.debug("... syncing file to '{}'".format(node))
260 self.salt.get_file(
261 node,
262 _source_path,
263 _target_path,
264 tgt_type="compound"
265 )
266 return _target_path
267
268 def prepare_script_on_active_nodes(self, script_filename):
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600269 # Prepare script
270 _p = os.path.join(pkg_dir, 'scripts', script_filename)
271 with open(_p, 'rt') as fd:
272 _script = fd.read().splitlines()
273 _storage_path = os.path.join(
274 config.salt_file_root, config.salt_scripts_folder
275 )
276 logger_cli.debug(
Alexb151fbe2019-04-22 16:53:30 -0500277 "... uploading script {} "
Alex3ebc5632019-04-18 16:47:18 -0500278 "to master's file cache folder: '{}'".format(
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600279 script_filename,
280 _storage_path
281 )
282 )
Alexe0c5b9e2019-04-23 18:51:23 -0500283 self.salt.mkdir(self.salt.master_node, _storage_path)
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600284 # Form cache, source and target path
285 _cache_path = os.path.join(_storage_path, script_filename)
286 _source_path = os.path.join(
287 'salt://',
288 config.salt_scripts_folder,
289 script_filename
290 )
291 _target_path = os.path.join(
292 '/root',
293 config.salt_scripts_folder,
294 script_filename
295 )
296
Alexb151fbe2019-04-22 16:53:30 -0500297 logger_cli.debug("... creating file in cache '{}'".format(_cache_path))
Alex3ebc5632019-04-18 16:47:18 -0500298 self.salt.f_touch_master(_cache_path)
299 self.salt.f_append_master(_cache_path, _script)
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600300 # command salt to copy file to minions
Alex3ebc5632019-04-18 16:47:18 -0500301 logger_cli.debug(
Alexb151fbe2019-04-22 16:53:30 -0500302 "... creating script target folder '{}'".format(
Alex3ebc5632019-04-18 16:47:18 -0500303 _cache_path
304 )
305 )
306 self.salt.mkdir(
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600307 self.active_nodes_compound,
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600308 os.path.join(
309 '/root',
310 config.salt_scripts_folder
311 ),
312 tgt_type="compound"
313 )
Alex3ebc5632019-04-18 16:47:18 -0500314 logger.debug("... syncing file to nodes")
315 self.salt.get_file(
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600316 self.active_nodes_compound,
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600317 _source_path,
318 _target_path,
319 tgt_type="compound"
320 )
Alexe0c5b9e2019-04-23 18:51:23 -0500321 # return path on nodes, just in case
322 return _target_path
323
324 def execute_script_on_node(self, node, script_filename, args=[]):
325 # Prepare path
326 _target_path = os.path.join(
327 '/root',
328 config.salt_scripts_folder,
329 script_filename
330 )
331
332 # execute script
333 logger.debug("... running script on '{}'".format(node))
334 # handle results for each node
335 _script_arguments = " ".join(args) if args else ""
336 self.not_responded = []
337 _r = self.salt.cmd(
338 node,
339 'cmd.run',
340 param='python {} {}'.format(_target_path, _script_arguments),
341 expr_form="compound"
342 )
343
344 # all false returns means that there is no response
345 self.not_responded = [_n for _n in _r.keys() if not _r[_n]]
346 return _r
347
348 def execute_script_on_active_nodes(self, script_filename, args=[]):
349 # Prepare path
350 _target_path = os.path.join(
351 '/root',
352 config.salt_scripts_folder,
353 script_filename
354 )
355
356 # execute script
Alexd0391d42019-05-21 18:48:55 -0500357 logger_cli.debug("... running script")
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600358 # handle results for each node
359 _script_arguments = " ".join(args) if args else ""
Alex Savatieievefa79c42019-03-14 19:14:04 -0500360 self.not_responded = []
361 _r = self.salt.cmd(
Alex Savatieiev01f0d7f2019-03-07 17:53:29 -0600362 self.active_nodes_compound,
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600363 'cmd.run',
364 param='python {} {}'.format(_target_path, _script_arguments),
365 expr_form="compound"
366 )
367
Alex Savatieievefa79c42019-03-14 19:14:04 -0500368 # all false returns means that there is no response
Alex3ebc5632019-04-18 16:47:18 -0500369 self.not_responded = [_n for _n in _r.keys() if not _r[_n]]
Alex Savatieievefa79c42019-03-14 19:14:04 -0500370 return _r
Alex Savatieiev9b2f6512019-02-20 18:05:00 -0600371
Alex836fac82019-08-22 13:36:16 -0500372 def execute_cmd_on_active_nodes(self, cmd):
373 # execute cmd
374 self.not_responded = []
375 _r = self.salt.cmd(
376 self.active_nodes_compound,
377 'cmd.run',
378 param=cmd,
379 expr_form="compound"
380 )
381
382 # all false returns means that there is no response
383 self.not_responded = [_n for _n in _r.keys() if not _r[_n]]
384 return _r
385
Alex Savatieievefa79c42019-03-14 19:14:04 -0500386 def is_node_available(self, node, log=True):
387 if node in self.skip_list:
388 if log:
389 logger_cli.info("-> node '{}' not active".format(node))
390 return False
391 elif node in self.not_responded:
392 if log:
393 logger_cli.info("-> node '{}' not responded".format(node))
394 return False
395 else:
396 return True
Alexe0c5b9e2019-04-23 18:51:23 -0500397
398
399salt_master = SaltNodes()