blob: dd6fbec8a55b352de4ffcc5133daf4370f95524a [file] [log] [blame]
savex4448e132018-04-25 15:51:14 +02001"""
2Module to handle interaction with salt
3"""
Alex Savatieiev63576832019-02-27 15:46:26 -06004import json
savex4448e132018-04-25 15:51:14 +02005import os
savex4448e132018-04-25 15:51:14 +02006import time
7
Alex3bc95f62020-03-05 17:00:04 -06008import requests
9
Alex3ebc5632019-04-18 16:47:18 -050010from cfg_checker.common import config, logger, logger_cli
11from cfg_checker.common.exception import InvalidReturnException, SaltException
Alex Savatieiev63576832019-02-27 15:46:26 -060012from cfg_checker.common.other import shell
Alex3ebc5632019-04-18 16:47:18 -050013
Alex Savatieiev63576832019-02-27 15:46:26 -060014
15def _extract_password(_raw):
Alex3bc95f62020-03-05 17:00:04 -060016 if not isinstance(_raw, str):
Alex Savatieiev63576832019-02-27 15:46:26 -060017 raise InvalidReturnException(_raw)
18 else:
19 try:
20 _json = json.loads(_raw)
Alex3ebc5632019-04-18 16:47:18 -050021 except ValueError:
Alex Savatieiev63576832019-02-27 15:46:26 -060022 raise SaltException(
Alex Savatieievf808cd22019-03-01 13:17:59 -060023 "# Return value is not a json: '{}'".format(_raw)
Alex Savatieiev63576832019-02-27 15:46:26 -060024 )
Alex3ebc5632019-04-18 16:47:18 -050025
Alex Savatieiev63576832019-02-27 15:46:26 -060026 return _json["local"]
27
28
29def get_remote_env_password():
30 """Uses ssh call with configured options to get password from salt master
31
32 :return: password string
33 """
34 _salt_cmd = "salt-call --out=json pillar.get _param:salt_api_password"
35 _ssh_cmd = ["ssh"]
36 # Build SSH cmd
37 if config.ssh_key:
38 _ssh_cmd.append("-i " + config.ssh_key)
39 if config.ssh_user:
40 _ssh_cmd.append(config.ssh_user+'@'+config.ssh_host)
41 else:
42 _ssh_cmd.append(config.ssh_host)
43 if config.ssh_uses_sudo:
44 _ssh_cmd.append("sudo")
Alex3ebc5632019-04-18 16:47:18 -050045
Alex Savatieiev63576832019-02-27 15:46:26 -060046 _ssh_cmd.append(_salt_cmd)
47 _ssh_cmd = " ".join(_ssh_cmd)
Alexb151fbe2019-04-22 16:53:30 -050048 logger_cli.debug("... calling salt: '{}'".format(_ssh_cmd))
Alexd0391d42019-05-21 18:48:55 -050049 try:
50 _result = shell(_ssh_cmd)
51 if len(_result) < 1:
52 raise InvalidReturnException(
53 "# Empty value returned for '{}".format(
54 _ssh_cmd
55 )
56 )
57 else:
58 return _extract_password(_result)
59 except OSError as e:
60 raise SaltException(
61 "Salt error calling '{}': '{}'\n"
62 "\nConsider checking 'SALT_ENV' "
63 "and '<pkg>/etc/<env>.env' files".format(_ssh_cmd, e.strerror)
64 )
Alex Savatieiev63576832019-02-27 15:46:26 -060065
Alex3ebc5632019-04-18 16:47:18 -050066
Alex Savatieiev63576832019-02-27 15:46:26 -060067def get_local_password():
68 """Calls salt locally to get password from the pillar
69
70 :return: password string
71 """
Alex3bc95f62020-03-05 17:00:04 -060072 _cmd = []
73 if config.ssh_uses_sudo:
74 _cmd = ["sudo"]
75 # salt commands
76 _cmd.append("salt-call")
77 _cmd.append("--out=json pillar.get _param:salt_api_password")
Alexd0391d42019-05-21 18:48:55 -050078 try:
Alex3bc95f62020-03-05 17:00:04 -060079 _result = shell(" ".join(_cmd))
Alexd0391d42019-05-21 18:48:55 -050080 except OSError as e:
81 raise SaltException(
82 "Salt error calling '{}': '{}'\n"
83 "\nConsider checking 'SALT_ENV' "
84 "and '<pkg>/etc/<env>.env' files".format(_cmd, e.strerror)
85 )
Alex Savatieiev63576832019-02-27 15:46:26 -060086 return _extract_password(_result)
savex4448e132018-04-25 15:51:14 +020087
88
89def list_to_target_string(node_list, separator):
90 result = ''
91 for node in node_list:
92 result += node + ' ' + separator + ' '
93 return result[:-(len(separator)+2)]
94
95
96class SaltRest(object):
97 _host = config.salt_host
98 _port = config.salt_port
99 uri = "http://" + config.salt_host + ":" + config.salt_port
100 _auth = {}
101
102 default_headers = {
103 'Accept': 'application/json',
104 'Content-Type': 'application/json',
105 'X-Auth-Token': None
106 }
107
108 def __init__(self):
109 self._token = self._login()
110 self.last_response = None
111
Alex3ebc5632019-04-18 16:47:18 -0500112 def get(
113 self,
114 path='',
115 headers=default_headers,
116 cookies=None,
117 timeout=None
118 ):
savex4448e132018-04-25 15:51:14 +0200119 _path = os.path.join(self.uri, path)
Alex Savatieievf808cd22019-03-01 13:17:59 -0600120 logger.debug("# GET '{}'\nHeaders: '{}'\nCookies: {}".format(
savex4448e132018-04-25 15:51:14 +0200121 _path,
122 headers,
123 cookies
124 ))
125 return requests.get(
126 _path,
127 headers=headers,
Alex Savatieievefa79c42019-03-14 19:14:04 -0500128 cookies=cookies,
129 timeout=timeout
savex4448e132018-04-25 15:51:14 +0200130 )
131
132 def post(self, data, path='', headers=default_headers, cookies=None):
133 if data is None:
134 data = {}
135 _path = os.path.join(self.uri, path)
136 if path == 'login':
Alex Savatieiev63576832019-02-27 15:46:26 -0600137 _data = str(data).replace(self._pass, "*****")
savex4448e132018-04-25 15:51:14 +0200138 else:
139 _data = data
Alex3ebc5632019-04-18 16:47:18 -0500140 logger.debug(
141 "# POST '{}'\nHeaders: '{}'\nCookies: {}\nBody: {}".format(
142 _path,
143 headers,
144 cookies,
145 _data
146 )
147 )
savex4448e132018-04-25 15:51:14 +0200148 return requests.post(
149 os.path.join(self.uri, path),
150 headers=headers,
151 json=data,
152 cookies=cookies
153 )
154
155 def _login(self):
Alex Savatieiev63576832019-02-27 15:46:26 -0600156 # if there is no password - try to get local, if this available
157 if config.salt_env == "local":
158 _pass = get_local_password()
159 else:
160 _pass = get_remote_env_password()
savex4448e132018-04-25 15:51:14 +0200161 login_payload = {
162 'username': config.salt_user,
Alex Savatieiev63576832019-02-27 15:46:26 -0600163 'password': _pass,
savex4448e132018-04-25 15:51:14 +0200164 'eauth': 'pam'
165 }
Alex Savatieiev63576832019-02-27 15:46:26 -0600166 self._pass = _pass
Alex Savatieievf808cd22019-03-01 13:17:59 -0600167 logger.debug("# Logging in to salt master...")
savex4448e132018-04-25 15:51:14 +0200168 _response = self.post(login_payload, path='login')
169
170 if _response.ok:
171 self._auth['response'] = _response.json()['return'][0]
172 self._auth['cookies'] = _response.cookies
173 self.default_headers['X-Auth-Token'] = \
174 self._auth['response']['token']
175 return self._auth['response']['token']
176 else:
177 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600178 "# HTTP:{}, Not authorized?".format(_response.status_code)
savex4448e132018-04-25 15:51:14 +0200179 )
180
181 def salt_request(self, fn, *args, **kwargs):
182 # if token will expire in 5 min, re-login
183 if self._auth['response']['expire'] < time.time() + 300:
184 self._auth['response']['X-Auth-Token'] = self._login()
185
186 _method = getattr(self, fn)
187 _response = _method(*args, **kwargs)
188 self.last_response = _response
189 _content = "..."
190 _len = len(_response.content)
191 if _len < 1024:
192 _content = _response.content
193 logger.debug(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600194 "# Response (HTTP {}/{}), {}: {}".format(
savex4448e132018-04-25 15:51:14 +0200195 _response.status_code,
196 _response.reason,
197 _len,
198 _content
199 )
200 )
201 if _response.ok:
202 return _response.json()['return']
203 else:
204 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600205 "# Salt Error: HTTP:{}, '{}'".format(
savex4448e132018-04-25 15:51:14 +0200206 _response.status_code,
207 _response.reason
208 )
209 )
210
211
212class SaltRemote(SaltRest):
Alexe0c5b9e2019-04-23 18:51:23 -0500213 master_node = ""
214
savex4448e132018-04-25 15:51:14 +0200215 def __init__(self):
216 super(SaltRemote, self).__init__()
217
218 def cmd(
219 self,
220 tgt,
221 fun,
222 param=None,
223 client='local',
224 kwarg=None,
225 expr_form=None,
226 tgt_type=None,
227 timeout=None
228 ):
229 _timeout = timeout if timeout is not None else config.salt_timeout
230 _payload = {
231 'fun': fun,
232 'tgt': tgt,
233 'client': client,
234 'timeout': _timeout
235 }
236
237 if expr_form:
238 _payload['expr_form'] = expr_form
239 if tgt_type:
240 _payload['tgt_type'] = tgt_type
241 if param:
242 _payload['arg'] = param
243 if kwarg:
244 _payload['kwarg'] = kwarg
245
246 _response = self.salt_request('post', [_payload])
247 if isinstance(_response, list):
248 return _response[0]
249 else:
250 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600251 "# Unexpected response from from salt-api/LocalClient: "
savex4448e132018-04-25 15:51:14 +0200252 "{}".format(_response)
253 )
254
255 def run(self, fun, kwarg=None):
256 _payload = {
257 'client': 'runner',
258 'fun': fun,
259 'timeout': config.salt_timeout
260 }
261
262 if kwarg:
263 _payload['kwarg'] = kwarg
264
265 _response = self.salt_request('post', [_payload])
266 if isinstance(_response, list):
267 return _response[0]
268 else:
269 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600270 "# Unexpected response from from salt-api/RunnerClient: "
savex4448e132018-04-25 15:51:14 +0200271 "{}".format(_response)
272 )
273
274 def wheel(self, fun, arg=None, kwarg=None):
275 _payload = {
276 'client': 'wheel',
277 'fun': fun,
278 'timeout': config.salt_timeout
279 }
280
281 if arg:
282 _payload['arg'] = arg
283 if kwarg:
284 _payload['kwarg'] = kwarg
285
286 _response = self.salt_request('post', _payload)['data']
287 if _response['success']:
288 return _response
289 else:
290 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600291 "# Salt Error: '{}'".format(_response['return']))
savex4448e132018-04-25 15:51:14 +0200292
293 def pillar_request(self, node_target, pillar_submodule, argument):
294 # example cli: 'salt "ctl01*" pillar.keys rsyslog'
295 _type = "compound"
296 if isinstance(node_target, list):
297 _type = "list"
298 return self.cmd(
299 node_target,
300 "pillar." + pillar_submodule,
301 argument,
302 expr_form=_type
303 )
304
305 def pillar_keys(self, node_target, argument):
306 return self.pillar_request(node_target, 'keys', argument)
307
308 def pillar_get(self, node_target, argument):
309 return self.pillar_request(node_target, 'get', argument)
310
311 def pillar_data(self, node_target, argument):
312 return self.pillar_request(node_target, 'data', argument)
313
314 def pillar_raw(self, node_target, argument):
315 return self.pillar_request(node_target, 'raw', argument)
316
317 def list_minions(self):
318 """
319 Fails in salt version 2016.3.8
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600320 Works starting from 2017.7.7
savex4448e132018-04-25 15:51:14 +0200321 api returns dict of minions with grains
322 """
Alex Savatieievefa79c42019-03-14 19:14:04 -0500323 try:
324 _r = self.salt_request('get', 'minions', timeout=10)
Alex3ebc5632019-04-18 16:47:18 -0500325 except requests.exceptions.ReadTimeout:
Alex Savatieievefa79c42019-03-14 19:14:04 -0500326 logger_cli.debug("... timeout waiting list minions from Salt API")
327 _r = None
328 return _r[0] if _r else None
savex4448e132018-04-25 15:51:14 +0200329
330 def list_keys(self):
331 """
332 Fails in salt version 2016.3.8
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600333 Works starting from 2017.7.7
savex4448e132018-04-25 15:51:14 +0200334 api should return dict:
335 {
336 'local': [],
337 'minions': [],
338 'minions_denied': [],
339 'minions_pre': [],
340 'minions_rejected': [],
341 }
342 """
343 return self.salt_request('get', path='keys')
344
345 def get_status(self):
346 """
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600347 Fails in salt version 2017.7.7
savex4448e132018-04-25 15:51:14 +0200348 'runner' client is the equivalent of 'salt-run'
349 Returns the
350 """
351 return self.run(
352 'manage.status',
353 kwarg={'timeout': 10}
354 )
355
356 def get_active_nodes(self):
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600357 """Used when other minion list metods fail
Alex3ebc5632019-04-18 16:47:18 -0500358
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600359 :return: json result from salt test.ping
360 """
savex4448e132018-04-25 15:51:14 +0200361 if config.skip_nodes:
Alex Savatieievf808cd22019-03-01 13:17:59 -0600362 logger.info("# Nodes to be skipped: {0}".format(config.skip_nodes))
Alex Savatieievefa79c42019-03-14 19:14:04 -0500363 _r = self.cmd(
savex4448e132018-04-25 15:51:14 +0200364 '* and not ' + list_to_target_string(
365 config.skip_nodes,
366 'and not'
367 ),
368 'test.ping',
369 expr_form='compound')
370 else:
Alex Savatieievefa79c42019-03-14 19:14:04 -0500371 _r = self.cmd('*', 'test.ping')
Alex3ebc5632019-04-18 16:47:18 -0500372 # Return all nodes that responded
Alex Savatieievefa79c42019-03-14 19:14:04 -0500373 return [node for node in _r.keys() if _r[node]]
savex4448e132018-04-25 15:51:14 +0200374
375 def get_monitoring_ip(self, param_name):
376 salt_output = self.cmd(
377 'docker:client:stack:monitoring',
378 'pillar.get',
379 param=param_name,
380 expr_form='pillar')
381 return salt_output[salt_output.keys()[0]]
382
383 def f_touch_master(self, path, makedirs=True):
384 _kwarg = {
385 "makedirs": makedirs
386 }
387 salt_output = self.cmd(
Alexe0c5b9e2019-04-23 18:51:23 -0500388 self.master_node,
savex4448e132018-04-25 15:51:14 +0200389 "file.touch",
390 param=path,
391 kwarg=_kwarg
392 )
Alex3bc95f62020-03-05 17:00:04 -0600393 return [*salt_output.values()][0]
savex4448e132018-04-25 15:51:14 +0200394
395 def f_append_master(self, path, strings_list, makedirs=True):
396 _kwarg = {
397 "makedirs": makedirs
398 }
399 _args = [path]
400 _args.extend(strings_list)
401 salt_output = self.cmd(
Alexe0c5b9e2019-04-23 18:51:23 -0500402 self.master_node,
savex4448e132018-04-25 15:51:14 +0200403 "file.write",
404 param=_args,
405 kwarg=_kwarg
406 )
Alex3bc95f62020-03-05 17:00:04 -0600407 return [*salt_output.values()][0]
savex4448e132018-04-25 15:51:14 +0200408
409 def mkdir(self, target, path, tgt_type=None):
410 salt_output = self.cmd(
411 target,
412 "file.mkdir",
413 param=path,
414 expr_form=tgt_type
415 )
416 return salt_output
417
418 def f_manage_file(self, target_path, source,
419 sfn='', ret='{}',
420 source_hash={},
421 user='root', group='root', backup_mode='755',
422 show_diff='base',
423 contents='', makedirs=True):
424 """
425 REST variation of file.get_managed
426 CLI execution goes like this (10 agrs):
Alex3ebc5632019-04-18 16:47:18 -0500427 salt cfg01\\* file.manage_file /root/test_scripts/pkg_versions.py
savex4448e132018-04-25 15:51:14 +0200428 '' '{}' /root/diff_pkg_version.py
429 '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' base ''
430 makedirs=True
431 param: name - target file placement when managed
432 param: source - source for the file
433 """
434 _source_hash = {
435 "hash_type": "md5",
436 "hsum": 000
437 }
438 _arg = [
439 target_path,
440 sfn,
441 ret,
442 source,
443 _source_hash,
444 user,
445 group,
446 backup_mode,
447 show_diff,
448 contents
449 ]
450 _kwarg = {
451 "makedirs": makedirs
452 }
453 salt_output = self.cmd(
Alexe0c5b9e2019-04-23 18:51:23 -0500454 self.master_node,
savex4448e132018-04-25 15:51:14 +0200455 "file.manage_file",
456 param=_arg,
457 kwarg=_kwarg
458 )
Alex3bc95f62020-03-05 17:00:04 -0600459 return [*salt_output.values()][0]
savex4448e132018-04-25 15:51:14 +0200460
461 def cache_file(self, target, source_path):
462 salt_output = self.cmd(
463 target,
464 "cp.cache_file",
465 param=source_path
466 )
Alex3bc95f62020-03-05 17:00:04 -0600467 return [*salt_output.values()][0]
savex4448e132018-04-25 15:51:14 +0200468
469 def get_file(self, target, source_path, target_path, tgt_type=None):
470 return self.cmd(
471 target,
472 "cp.get_file",
473 param=[source_path, target_path],
474 expr_form=tgt_type
475 )
476
477 @staticmethod
478 def compound_string_from_list(nodes_list):
479 return " or ".join(nodes_list)