savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 1 | """ |
| 2 | Module to handle interaction with salt |
| 3 | """ |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 4 | import json |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 5 | import os |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 6 | import time |
| 7 | |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 8 | from cfg_checker.common import config, logger, logger_cli |
| 9 | from cfg_checker.common.exception import InvalidReturnException, SaltException |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 10 | from cfg_checker.common.other import shell |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 11 | |
| 12 | import requests |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 13 | |
| 14 | |
| 15 | def _extract_password(_raw): |
| 16 | if not isinstance(_raw, unicode): |
| 17 | raise InvalidReturnException(_raw) |
| 18 | else: |
| 19 | try: |
| 20 | _json = json.loads(_raw) |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 21 | except ValueError: |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 22 | raise SaltException( |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 23 | "# Return value is not a json: '{}'".format(_raw) |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 24 | ) |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 25 | |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 26 | return _json["local"] |
| 27 | |
| 28 | |
| 29 | def 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") |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 45 | |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 46 | _ssh_cmd.append(_salt_cmd) |
| 47 | _ssh_cmd = " ".join(_ssh_cmd) |
Alex | b151fbe | 2019-04-22 16:53:30 -0500 | [diff] [blame^] | 48 | logger_cli.debug("... calling salt: '{}'".format(_ssh_cmd)) |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 49 | _result = shell(_ssh_cmd) |
| 50 | if len(_result) < 1: |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 51 | raise InvalidReturnException("# Empty value returned for '{}".format( |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 52 | _ssh_cmd |
| 53 | )) |
| 54 | else: |
| 55 | return _extract_password(_result) |
| 56 | |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 57 | |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 58 | def 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) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 66 | |
| 67 | |
| 68 | def 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 | |
| 75 | class 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 | |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 91 | def get( |
| 92 | self, |
| 93 | path='', |
| 94 | headers=default_headers, |
| 95 | cookies=None, |
| 96 | timeout=None |
| 97 | ): |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 98 | _path = os.path.join(self.uri, path) |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 99 | logger.debug("# GET '{}'\nHeaders: '{}'\nCookies: {}".format( |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 100 | _path, |
| 101 | headers, |
| 102 | cookies |
| 103 | )) |
| 104 | return requests.get( |
| 105 | _path, |
| 106 | headers=headers, |
Alex Savatieiev | efa79c4 | 2019-03-14 19:14:04 -0500 | [diff] [blame] | 107 | cookies=cookies, |
| 108 | timeout=timeout |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 109 | ) |
| 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 Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 116 | _data = str(data).replace(self._pass, "*****") |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 117 | else: |
| 118 | _data = data |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 119 | logger.debug( |
| 120 | "# POST '{}'\nHeaders: '{}'\nCookies: {}\nBody: {}".format( |
| 121 | _path, |
| 122 | headers, |
| 123 | cookies, |
| 124 | _data |
| 125 | ) |
| 126 | ) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 127 | 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 Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 135 | # 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() |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 140 | login_payload = { |
| 141 | 'username': config.salt_user, |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 142 | 'password': _pass, |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 143 | 'eauth': 'pam' |
| 144 | } |
Alex Savatieiev | 6357683 | 2019-02-27 15:46:26 -0600 | [diff] [blame] | 145 | self._pass = _pass |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 146 | logger.debug("# Logging in to salt master...") |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 147 | _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 Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 157 | "# HTTP:{}, Not authorized?".format(_response.status_code) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 158 | ) |
| 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 Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 173 | "# Response (HTTP {}/{}), {}: {}".format( |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 174 | _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 Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 184 | "# Salt Error: HTTP:{}, '{}'".format( |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 185 | _response.status_code, |
| 186 | _response.reason |
| 187 | ) |
| 188 | ) |
| 189 | |
| 190 | |
| 191 | class 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 Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 228 | "# Unexpected response from from salt-api/LocalClient: " |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 229 | "{}".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 Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 247 | "# Unexpected response from from salt-api/RunnerClient: " |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 248 | "{}".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 Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 268 | "# Salt Error: '{}'".format(_response['return'])) |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 269 | |
| 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 Savatieiev | 9df93a9 | 2019-02-27 17:40:16 -0600 | [diff] [blame] | 297 | Works starting from 2017.7.7 |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 298 | api returns dict of minions with grains |
| 299 | """ |
Alex Savatieiev | efa79c4 | 2019-03-14 19:14:04 -0500 | [diff] [blame] | 300 | try: |
| 301 | _r = self.salt_request('get', 'minions', timeout=10) |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 302 | except requests.exceptions.ReadTimeout: |
Alex Savatieiev | efa79c4 | 2019-03-14 19:14:04 -0500 | [diff] [blame] | 303 | logger_cli.debug("... timeout waiting list minions from Salt API") |
| 304 | _r = None |
| 305 | return _r[0] if _r else None |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 306 | |
| 307 | def list_keys(self): |
| 308 | """ |
| 309 | Fails in salt version 2016.3.8 |
Alex Savatieiev | 9df93a9 | 2019-02-27 17:40:16 -0600 | [diff] [blame] | 310 | Works starting from 2017.7.7 |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 311 | 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 Savatieiev | 9df93a9 | 2019-02-27 17:40:16 -0600 | [diff] [blame] | 324 | Fails in salt version 2017.7.7 |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 325 | '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 Savatieiev | 9df93a9 | 2019-02-27 17:40:16 -0600 | [diff] [blame] | 334 | """Used when other minion list metods fail |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 335 | |
Alex Savatieiev | 9df93a9 | 2019-02-27 17:40:16 -0600 | [diff] [blame] | 336 | :return: json result from salt test.ping |
| 337 | """ |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 338 | if config.skip_nodes: |
Alex Savatieiev | f808cd2 | 2019-03-01 13:17:59 -0600 | [diff] [blame] | 339 | logger.info("# Nodes to be skipped: {0}".format(config.skip_nodes)) |
Alex Savatieiev | efa79c4 | 2019-03-14 19:14:04 -0500 | [diff] [blame] | 340 | _r = self.cmd( |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 341 | '* and not ' + list_to_target_string( |
| 342 | config.skip_nodes, |
| 343 | 'and not' |
| 344 | ), |
| 345 | 'test.ping', |
| 346 | expr_form='compound') |
| 347 | else: |
Alex Savatieiev | efa79c4 | 2019-03-14 19:14:04 -0500 | [diff] [blame] | 348 | _r = self.cmd('*', 'test.ping') |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 349 | # Return all nodes that responded |
Alex Savatieiev | efa79c4 | 2019-03-14 19:14:04 -0500 | [diff] [blame] | 350 | return [node for node in _r.keys() if _r[node]] |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 351 | |
| 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): |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 404 | salt cfg01\\* file.manage_file /root/test_scripts/pkg_versions.py |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 405 | '' '{}' /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) |