blob: 2927e284b7963e9f9732aa515ad6dbe230ea120b [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
Alex3ebc5632019-04-18 16:47:18 -05008from cfg_checker.common import config, logger, logger_cli
9from cfg_checker.common.exception import InvalidReturnException, SaltException
Alex Savatieiev63576832019-02-27 15:46:26 -060010from cfg_checker.common.other import shell
Alex3ebc5632019-04-18 16:47:18 -050011
12import requests
Alex Savatieiev63576832019-02-27 15:46:26 -060013
14
15def _extract_password(_raw):
16 if not isinstance(_raw, unicode):
17 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))
Alex Savatieiev63576832019-02-27 15:46:26 -060049 _result = shell(_ssh_cmd)
50 if len(_result) < 1:
Alex Savatieievf808cd22019-03-01 13:17:59 -060051 raise InvalidReturnException("# Empty value returned for '{}".format(
Alex Savatieiev63576832019-02-27 15:46:26 -060052 _ssh_cmd
53 ))
54 else:
55 return _extract_password(_result)
56
Alex3ebc5632019-04-18 16:47:18 -050057
Alex Savatieiev63576832019-02-27 15:46:26 -060058def get_local_password():
59 """Calls salt locally to get password from the pillar
60
61 :return: password string
62 """
63 _cmd = "salt-call --out=json pillar.get _param:salt_api_password"
64 _result = shell(_cmd)
65 return _extract_password(_result)
savex4448e132018-04-25 15:51:14 +020066
67
68def list_to_target_string(node_list, separator):
69 result = ''
70 for node in node_list:
71 result += node + ' ' + separator + ' '
72 return result[:-(len(separator)+2)]
73
74
75class SaltRest(object):
76 _host = config.salt_host
77 _port = config.salt_port
78 uri = "http://" + config.salt_host + ":" + config.salt_port
79 _auth = {}
80
81 default_headers = {
82 'Accept': 'application/json',
83 'Content-Type': 'application/json',
84 'X-Auth-Token': None
85 }
86
87 def __init__(self):
88 self._token = self._login()
89 self.last_response = None
90
Alex3ebc5632019-04-18 16:47:18 -050091 def get(
92 self,
93 path='',
94 headers=default_headers,
95 cookies=None,
96 timeout=None
97 ):
savex4448e132018-04-25 15:51:14 +020098 _path = os.path.join(self.uri, path)
Alex Savatieievf808cd22019-03-01 13:17:59 -060099 logger.debug("# GET '{}'\nHeaders: '{}'\nCookies: {}".format(
savex4448e132018-04-25 15:51:14 +0200100 _path,
101 headers,
102 cookies
103 ))
104 return requests.get(
105 _path,
106 headers=headers,
Alex Savatieievefa79c42019-03-14 19:14:04 -0500107 cookies=cookies,
108 timeout=timeout
savex4448e132018-04-25 15:51:14 +0200109 )
110
111 def post(self, data, path='', headers=default_headers, cookies=None):
112 if data is None:
113 data = {}
114 _path = os.path.join(self.uri, path)
115 if path == 'login':
Alex Savatieiev63576832019-02-27 15:46:26 -0600116 _data = str(data).replace(self._pass, "*****")
savex4448e132018-04-25 15:51:14 +0200117 else:
118 _data = data
Alex3ebc5632019-04-18 16:47:18 -0500119 logger.debug(
120 "# POST '{}'\nHeaders: '{}'\nCookies: {}\nBody: {}".format(
121 _path,
122 headers,
123 cookies,
124 _data
125 )
126 )
savex4448e132018-04-25 15:51:14 +0200127 return requests.post(
128 os.path.join(self.uri, path),
129 headers=headers,
130 json=data,
131 cookies=cookies
132 )
133
134 def _login(self):
Alex Savatieiev63576832019-02-27 15:46:26 -0600135 # if there is no password - try to get local, if this available
136 if config.salt_env == "local":
137 _pass = get_local_password()
138 else:
139 _pass = get_remote_env_password()
savex4448e132018-04-25 15:51:14 +0200140 login_payload = {
141 'username': config.salt_user,
Alex Savatieiev63576832019-02-27 15:46:26 -0600142 'password': _pass,
savex4448e132018-04-25 15:51:14 +0200143 'eauth': 'pam'
144 }
Alex Savatieiev63576832019-02-27 15:46:26 -0600145 self._pass = _pass
Alex Savatieievf808cd22019-03-01 13:17:59 -0600146 logger.debug("# Logging in to salt master...")
savex4448e132018-04-25 15:51:14 +0200147 _response = self.post(login_payload, path='login')
148
149 if _response.ok:
150 self._auth['response'] = _response.json()['return'][0]
151 self._auth['cookies'] = _response.cookies
152 self.default_headers['X-Auth-Token'] = \
153 self._auth['response']['token']
154 return self._auth['response']['token']
155 else:
156 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600157 "# HTTP:{}, Not authorized?".format(_response.status_code)
savex4448e132018-04-25 15:51:14 +0200158 )
159
160 def salt_request(self, fn, *args, **kwargs):
161 # if token will expire in 5 min, re-login
162 if self._auth['response']['expire'] < time.time() + 300:
163 self._auth['response']['X-Auth-Token'] = self._login()
164
165 _method = getattr(self, fn)
166 _response = _method(*args, **kwargs)
167 self.last_response = _response
168 _content = "..."
169 _len = len(_response.content)
170 if _len < 1024:
171 _content = _response.content
172 logger.debug(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600173 "# Response (HTTP {}/{}), {}: {}".format(
savex4448e132018-04-25 15:51:14 +0200174 _response.status_code,
175 _response.reason,
176 _len,
177 _content
178 )
179 )
180 if _response.ok:
181 return _response.json()['return']
182 else:
183 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600184 "# Salt Error: HTTP:{}, '{}'".format(
savex4448e132018-04-25 15:51:14 +0200185 _response.status_code,
186 _response.reason
187 )
188 )
189
190
191class SaltRemote(SaltRest):
192 def __init__(self):
193 super(SaltRemote, self).__init__()
194
195 def cmd(
196 self,
197 tgt,
198 fun,
199 param=None,
200 client='local',
201 kwarg=None,
202 expr_form=None,
203 tgt_type=None,
204 timeout=None
205 ):
206 _timeout = timeout if timeout is not None else config.salt_timeout
207 _payload = {
208 'fun': fun,
209 'tgt': tgt,
210 'client': client,
211 'timeout': _timeout
212 }
213
214 if expr_form:
215 _payload['expr_form'] = expr_form
216 if tgt_type:
217 _payload['tgt_type'] = tgt_type
218 if param:
219 _payload['arg'] = param
220 if kwarg:
221 _payload['kwarg'] = kwarg
222
223 _response = self.salt_request('post', [_payload])
224 if isinstance(_response, list):
225 return _response[0]
226 else:
227 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600228 "# Unexpected response from from salt-api/LocalClient: "
savex4448e132018-04-25 15:51:14 +0200229 "{}".format(_response)
230 )
231
232 def run(self, fun, kwarg=None):
233 _payload = {
234 'client': 'runner',
235 'fun': fun,
236 'timeout': config.salt_timeout
237 }
238
239 if kwarg:
240 _payload['kwarg'] = kwarg
241
242 _response = self.salt_request('post', [_payload])
243 if isinstance(_response, list):
244 return _response[0]
245 else:
246 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600247 "# Unexpected response from from salt-api/RunnerClient: "
savex4448e132018-04-25 15:51:14 +0200248 "{}".format(_response)
249 )
250
251 def wheel(self, fun, arg=None, kwarg=None):
252 _payload = {
253 'client': 'wheel',
254 'fun': fun,
255 'timeout': config.salt_timeout
256 }
257
258 if arg:
259 _payload['arg'] = arg
260 if kwarg:
261 _payload['kwarg'] = kwarg
262
263 _response = self.salt_request('post', _payload)['data']
264 if _response['success']:
265 return _response
266 else:
267 raise EnvironmentError(
Alex Savatieievf808cd22019-03-01 13:17:59 -0600268 "# Salt Error: '{}'".format(_response['return']))
savex4448e132018-04-25 15:51:14 +0200269
270 def pillar_request(self, node_target, pillar_submodule, argument):
271 # example cli: 'salt "ctl01*" pillar.keys rsyslog'
272 _type = "compound"
273 if isinstance(node_target, list):
274 _type = "list"
275 return self.cmd(
276 node_target,
277 "pillar." + pillar_submodule,
278 argument,
279 expr_form=_type
280 )
281
282 def pillar_keys(self, node_target, argument):
283 return self.pillar_request(node_target, 'keys', argument)
284
285 def pillar_get(self, node_target, argument):
286 return self.pillar_request(node_target, 'get', argument)
287
288 def pillar_data(self, node_target, argument):
289 return self.pillar_request(node_target, 'data', argument)
290
291 def pillar_raw(self, node_target, argument):
292 return self.pillar_request(node_target, 'raw', argument)
293
294 def list_minions(self):
295 """
296 Fails in salt version 2016.3.8
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600297 Works starting from 2017.7.7
savex4448e132018-04-25 15:51:14 +0200298 api returns dict of minions with grains
299 """
Alex Savatieievefa79c42019-03-14 19:14:04 -0500300 try:
301 _r = self.salt_request('get', 'minions', timeout=10)
Alex3ebc5632019-04-18 16:47:18 -0500302 except requests.exceptions.ReadTimeout:
Alex Savatieievefa79c42019-03-14 19:14:04 -0500303 logger_cli.debug("... timeout waiting list minions from Salt API")
304 _r = None
305 return _r[0] if _r else None
savex4448e132018-04-25 15:51:14 +0200306
307 def list_keys(self):
308 """
309 Fails in salt version 2016.3.8
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600310 Works starting from 2017.7.7
savex4448e132018-04-25 15:51:14 +0200311 api should return dict:
312 {
313 'local': [],
314 'minions': [],
315 'minions_denied': [],
316 'minions_pre': [],
317 'minions_rejected': [],
318 }
319 """
320 return self.salt_request('get', path='keys')
321
322 def get_status(self):
323 """
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600324 Fails in salt version 2017.7.7
savex4448e132018-04-25 15:51:14 +0200325 'runner' client is the equivalent of 'salt-run'
326 Returns the
327 """
328 return self.run(
329 'manage.status',
330 kwarg={'timeout': 10}
331 )
332
333 def get_active_nodes(self):
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600334 """Used when other minion list metods fail
Alex3ebc5632019-04-18 16:47:18 -0500335
Alex Savatieiev9df93a92019-02-27 17:40:16 -0600336 :return: json result from salt test.ping
337 """
savex4448e132018-04-25 15:51:14 +0200338 if config.skip_nodes:
Alex Savatieievf808cd22019-03-01 13:17:59 -0600339 logger.info("# Nodes to be skipped: {0}".format(config.skip_nodes))
Alex Savatieievefa79c42019-03-14 19:14:04 -0500340 _r = self.cmd(
savex4448e132018-04-25 15:51:14 +0200341 '* and not ' + list_to_target_string(
342 config.skip_nodes,
343 'and not'
344 ),
345 'test.ping',
346 expr_form='compound')
347 else:
Alex Savatieievefa79c42019-03-14 19:14:04 -0500348 _r = self.cmd('*', 'test.ping')
Alex3ebc5632019-04-18 16:47:18 -0500349 # Return all nodes that responded
Alex Savatieievefa79c42019-03-14 19:14:04 -0500350 return [node for node in _r.keys() if _r[node]]
savex4448e132018-04-25 15:51:14 +0200351
352 def get_monitoring_ip(self, param_name):
353 salt_output = self.cmd(
354 'docker:client:stack:monitoring',
355 'pillar.get',
356 param=param_name,
357 expr_form='pillar')
358 return salt_output[salt_output.keys()[0]]
359
360 def f_touch_master(self, path, makedirs=True):
361 _kwarg = {
362 "makedirs": makedirs
363 }
364 salt_output = self.cmd(
365 "cfg01*",
366 "file.touch",
367 param=path,
368 kwarg=_kwarg
369 )
370 return salt_output[salt_output.keys()[0]]
371
372 def f_append_master(self, path, strings_list, makedirs=True):
373 _kwarg = {
374 "makedirs": makedirs
375 }
376 _args = [path]
377 _args.extend(strings_list)
378 salt_output = self.cmd(
379 "cfg01*",
380 "file.write",
381 param=_args,
382 kwarg=_kwarg
383 )
384 return salt_output[salt_output.keys()[0]]
385
386 def mkdir(self, target, path, tgt_type=None):
387 salt_output = self.cmd(
388 target,
389 "file.mkdir",
390 param=path,
391 expr_form=tgt_type
392 )
393 return salt_output
394
395 def f_manage_file(self, target_path, source,
396 sfn='', ret='{}',
397 source_hash={},
398 user='root', group='root', backup_mode='755',
399 show_diff='base',
400 contents='', makedirs=True):
401 """
402 REST variation of file.get_managed
403 CLI execution goes like this (10 agrs):
Alex3ebc5632019-04-18 16:47:18 -0500404 salt cfg01\\* file.manage_file /root/test_scripts/pkg_versions.py
savex4448e132018-04-25 15:51:14 +0200405 '' '{}' /root/diff_pkg_version.py
406 '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' base ''
407 makedirs=True
408 param: name - target file placement when managed
409 param: source - source for the file
410 """
411 _source_hash = {
412 "hash_type": "md5",
413 "hsum": 000
414 }
415 _arg = [
416 target_path,
417 sfn,
418 ret,
419 source,
420 _source_hash,
421 user,
422 group,
423 backup_mode,
424 show_diff,
425 contents
426 ]
427 _kwarg = {
428 "makedirs": makedirs
429 }
430 salt_output = self.cmd(
431 "cfg01*",
432 "file.manage_file",
433 param=_arg,
434 kwarg=_kwarg
435 )
436 return salt_output[salt_output.keys()[0]]
437
438 def cache_file(self, target, source_path):
439 salt_output = self.cmd(
440 target,
441 "cp.cache_file",
442 param=source_path
443 )
444 return salt_output[salt_output.keys()[0]]
445
446 def get_file(self, target, source_path, target_path, tgt_type=None):
447 return self.cmd(
448 target,
449 "cp.get_file",
450 param=[source_path, target_path],
451 expr_form=tgt_type
452 )
453
454 @staticmethod
455 def compound_string_from_list(nodes_list):
456 return " or ".join(nodes_list)