| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
""" Support class for IBM SVC ansible modules """ |
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
|
| 11 |
__metaclass__ = type |
| 12 |
|
| 13 |
import json |
| 14 |
import logging |
| 15 |
import uuid |
| 16 |
import inspect |
| 17 |
from time import sleep |
| 18 |
|
| 19 |
from ansible.module_utils.urls import open_url |
| 20 |
from ansible.module_utils.six.moves.urllib.parse import quote |
| 21 |
from ansible.module_utils.six.moves.urllib.error import HTTPError |
| 22 |
|
| 23 |
COLLECTION_VERSION = "3.3.0" |
| 24 |
TIMEOUT = 600 |
| 25 |
|
| 26 |
|
| 27 |
def svc_argument_spec(): |
| 28 |
""" |
| 29 |
Returns argument_spec of options common to ibm_svc_*-modules |
| 30 |
|
| 31 |
:returns: argument_spec |
| 32 |
:rtype: dict |
| 33 |
""" |
| 34 |
return dict( |
| 35 |
clustername=dict(type='str', required=True), |
| 36 |
domain=dict(type='str', default=None), |
| 37 |
validate_certs=dict(type='bool', default=False), |
| 38 |
username=dict(type='str'), |
| 39 |
password=dict(type='str', no_log=True), |
| 40 |
log_path=dict(type='str'), |
| 41 |
token=dict(type='str', no_log=True) |
| 42 |
) |
| 43 |
|
| 44 |
|
| 45 |
def svc_ssh_argument_spec(): |
| 46 |
""" |
| 47 |
Returns argument_spec of options common to ibm_svcinfo_command |
| 48 |
and ibm_svctask_command modules |
| 49 |
|
| 50 |
:returns: argument_spec |
| 51 |
:rtype: dict |
| 52 |
""" |
| 53 |
return dict( |
| 54 |
clustername=dict(type='str', required=True), |
| 55 |
domain=dict(type='str', required=False), |
| 56 |
username=dict(type='str', required=True), |
| 57 |
password=dict(type='str', required=True, no_log=True), |
| 58 |
log_path=dict(type='str') |
| 59 |
) |
| 60 |
|
| 61 |
|
| 62 |
def strtobool(val): |
| 63 |
''' |
| 64 |
Converts a string representation to boolean. |
| 65 |
|
| 66 |
This is a built-in function available in python till the version 3.9 under disutils.util |
| 67 |
but this has been deprecated in 3.10 and may not be available in future python releases |
| 68 |
so adding the source code here. |
| 69 |
''' |
| 70 |
if val in {'y', 'yes', 't', 'true', 'on', '1'}: |
| 71 |
return 1 |
| 72 |
elif val in {'n', 'no', 'f', 'false', 'off', '0'}: |
| 73 |
return 0 |
| 74 |
else: |
| 75 |
raise ValueError("invalid truth value %r" % (val,)) |
| 76 |
|
| 77 |
|
| 78 |
def get_logger(module_name, log_file_name, log_level=logging.INFO): |
| 79 |
FORMAT = '%(asctime)s.%(msecs)03d %(levelname)5s %(thread)d %(filename)s:%(funcName)s():%(lineno)s %(message)s' |
| 80 |
DATEFORMAT = '%Y-%m-%dT%H:%M:%S' |
| 81 |
log_path = 'IBMSV_ansible_collections.log' |
| 82 |
if log_file_name: |
| 83 |
log_path = log_file_name |
| 84 |
logging.basicConfig(filename=log_path, format=FORMAT, datefmt=DATEFORMAT) |
| 85 |
log = logging.getLogger(module_name) |
| 86 |
log.setLevel(log_level) |
| 87 |
return log |
| 88 |
|
| 89 |
|
| 90 |
def is_supported_version(current_version, supported_version): |
| 91 |
current_parts = list(map(int, current_version.split('.'))) |
| 92 |
supported_parts = list(map(int, supported_version.split('.'))) |
| 93 |
|
| 94 |
for current_part, supported_part in zip(current_parts, supported_parts): |
| 95 |
if current_part < supported_part: |
| 96 |
return False |
| 97 |
elif current_part > supported_part: |
| 98 |
return True |
| 99 |
|
| 100 |
return True |
| 101 |
|
| 102 |
|
| 103 |
def is_feature_supported(feature, version): |
| 104 |
''' |
| 105 |
This function contains a dictionary of mapping of CLI/feature with its earliest |
| 106 |
supported SVC version. |
| 107 |
''' |
| 108 |
|
| 109 |
|
| 110 |
feature_version_mapping = { |
| 111 |
'chvolume': '9.1.0.0', |
| 112 |
'certstore_cmds': '9.1.0.0' |
| 113 |
} |
| 114 |
|
| 115 |
return is_supported_version(version, feature_version_mapping[feature]) |
| 116 |
|
| 117 |
|
| 118 |
class IBMSVCRestApi(object): |
| 119 |
""" Communicate with SVC through RestApi |
| 120 |
SVC commands usually have the format |
| 121 |
$ command -opt1 value1 -opt2 value2 arg1 arg2 arg3 |
| 122 |
to use the RestApi we transform this into |
| 123 |
https://host:7443/rest/command/arg1/arg2/arg3 |
| 124 |
data={'opt1':'value1', 'opt2':'value2'} |
| 125 |
""" |
| 126 |
|
| 127 |
def __init__(self, module, clustername, domain, username, password, |
| 128 |
validate_certs, log_path, token): |
| 129 |
""" Initialize module with what we need for initial connection |
| 130 |
:param clustername: name of the SVC cluster |
| 131 |
:type clustername: string |
| 132 |
:param domain: domain name to make a fully qualified host name |
| 133 |
:type domain: string |
| 134 |
:param username: SVC username |
| 135 |
:type username: string |
| 136 |
:param password: Password for user |
| 137 |
:type password: string |
| 138 |
:param validate_certs: whether or not the connection is insecure |
| 139 |
:type validate_certs: bool |
| 140 |
""" |
| 141 |
self.module = module |
| 142 |
self.clustername = clustername |
| 143 |
self.domain = domain |
| 144 |
self.username = username |
| 145 |
self.password = password |
| 146 |
self.validate_certs = validate_certs |
| 147 |
self.token = token |
| 148 |
|
| 149 |
|
| 150 |
log = get_logger(self.__class__.__name__, log_path) |
| 151 |
self.log = log.info |
| 152 |
|
| 153 |
|
| 154 |
if self.token is None: |
| 155 |
if not self.username or not self.password: |
| 156 |
self.module.fail_json(msg="You must pass in either pre-acquired token" |
| 157 |
" or username/password to generate new token") |
| 158 |
self.token = self._svc_authorize() |
| 159 |
else: |
| 160 |
self.log("Using user-provided token for authentication.") |
| 161 |
|
| 162 |
if not self.token: |
| 163 |
self.module.exit_json(msg='Failed to obtain access token', unreachable=True) |
| 164 |
|
| 165 |
@property |
| 166 |
def port(self): |
| 167 |
return getattr(self, '_port', None) or '7443' |
| 168 |
|
| 169 |
@property |
| 170 |
def protocol(self): |
| 171 |
return getattr(self, '_protocol', None) or 'https' |
| 172 |
|
| 173 |
@property |
| 174 |
def resturl(self): |
| 175 |
if self.domain: |
| 176 |
hostname = '%s.%s' % (self.clustername, self.domain) |
| 177 |
else: |
| 178 |
hostname = self.clustername |
| 179 |
return (getattr(self, '_resturl', None) |
| 180 |
or "{protocol}://{host}:{port}/rest".format( |
| 181 |
protocol=self.protocol, host=hostname, port=self.port)) |
| 182 |
|
| 183 |
@property |
| 184 |
def token(self): |
| 185 |
return getattr(self, '_token', None) or None |
| 186 |
|
| 187 |
@token.setter |
| 188 |
def token(self, value): |
| 189 |
return setattr(self, '_token', value) |
| 190 |
|
| 191 |
def _svc_rest(self, method, headers, cmd, cmdopts, cmdargs, timeout=TIMEOUT): |
| 192 |
""" Run SVC command with token info added into header |
| 193 |
:param method: http method, POST or GET |
| 194 |
:type method: string |
| 195 |
:param headers: http headers |
| 196 |
:type headers: dict |
| 197 |
:param cmd: svc command to run |
| 198 |
:type cmd: string |
| 199 |
:param cmdopts: svc command options, name parameter and value |
| 200 |
:type cmdopts: dict |
| 201 |
:param cmdargs: svc command arguments, non-named paramaters |
| 202 |
:type timeout: int |
| 203 |
:param timeout: open_url argument to set timeout for http gateway |
| 204 |
:return: dict of command results |
| 205 |
:rtype: dict |
| 206 |
""" |
| 207 |
|
| 208 |
|
| 209 |
r = { |
| 210 |
'url': None, |
| 211 |
'code': None, |
| 212 |
'err': None, |
| 213 |
'out': None, |
| 214 |
'data': None |
| 215 |
} |
| 216 |
|
| 217 |
postfix = cmd |
| 218 |
if cmdargs: |
| 219 |
postfix = '/'.join([postfix] + [quote(str(a)) for a in cmdargs]) |
| 220 |
url = '/'.join([self.resturl] + [postfix]) |
| 221 |
r['url'] = url |
| 222 |
self.log("_svc_rest: url=%s", url) |
| 223 |
|
| 224 |
payload = cmdopts if cmdopts else None |
| 225 |
data = self.module.jsonify(payload).encode('utf8') |
| 226 |
r['data'] = cmdopts |
| 227 |
self.log("_svc_rest: payload=%s", payload) |
| 228 |
|
| 229 |
try: |
| 230 |
o = open_url(url, method=method, headers=headers, timeout=timeout, |
| 231 |
validate_certs=self.validate_certs, data=bytes(data)) |
| 232 |
except HTTPError as e: |
| 233 |
self.log('_svc_rest: httperror %s', str(e)) |
| 234 |
r['code'] = e.getcode() |
| 235 |
r['out'] = e.read() |
| 236 |
r['err'] = f"HTTPError {str(e)}" |
| 237 |
return r |
| 238 |
except Exception as e: |
| 239 |
self.log('_svc_rest: exception : %s', str(e)) |
| 240 |
r['err'] = f"Exception {str(e)}" |
| 241 |
return r |
| 242 |
|
| 243 |
try: |
| 244 |
j = json.load(o) |
| 245 |
except ValueError as e: |
| 246 |
self.log("_svc_rest: value error pass: %s", str(e)) |
| 247 |
|
| 248 |
return r |
| 249 |
|
| 250 |
r['out'] = j |
| 251 |
return r |
| 252 |
|
| 253 |
def _svc_authorize(self): |
| 254 |
""" Obtain a token if we are authoized to connect |
| 255 |
:return: None or token string |
| 256 |
""" |
| 257 |
|
| 258 |
headers = { |
| 259 |
'Content-Type': 'application/json', |
| 260 |
'X-Auth-Username': self.username, |
| 261 |
'X-Auth-Password': self.password |
| 262 |
} |
| 263 |
|
| 264 |
max_retries = 3 |
| 265 |
|
| 266 |
for attempt in range(max_retries): |
| 267 |
rest = self._svc_rest(method='POST', headers=headers, cmd='auth', |
| 268 |
cmdopts=None, cmdargs=None) |
| 269 |
|
| 270 |
if rest.get('code') != 429: |
| 271 |
break |
| 272 |
|
| 273 |
self.log("Authorization attempt failed with 429. Retrying... (%d/%d)", attempt + 1, max_retries) |
| 274 |
sleep(2 ** attempt) |
| 275 |
attempt += 1 |
| 276 |
|
| 277 |
if rest.get('err'): |
| 278 |
return None |
| 279 |
|
| 280 |
out = rest['out'] |
| 281 |
if out and ('token' in out): |
| 282 |
try: |
| 283 |
rp_headers = { |
| 284 |
'Content-Type': 'application/json', |
| 285 |
'X-Auth-Token': out['token'] |
| 286 |
} |
| 287 |
rp_cmdopts = self.register_plugin_cmdopts() |
| 288 |
self._svc_rest(method='POST', headers=rp_headers, cmd="registerplugin", |
| 289 |
cmdopts=rp_cmdopts, cmdargs=None) |
| 290 |
except Exception: |
| 291 |
pass |
| 292 |
return out['token'] |
| 293 |
|
| 294 |
return None |
| 295 |
|
| 296 |
def _svc_token_wrap(self, cmd, cmdopts, cmdargs, timeout=TIMEOUT): |
| 297 |
""" Run SVC command with token info added into header |
| 298 |
:param cmd: svc command to run |
| 299 |
:type cmd: string |
| 300 |
:param cmdopts: svc command options, name parameter and value |
| 301 |
:type cmdopts: dict |
| 302 |
:param cmdargs: svc command arguments, non-named paramaters |
| 303 |
:type cmdargs: list |
| 304 |
:param timeout: open_url argument to set timeout for http gateway |
| 305 |
:type timeout: int |
| 306 |
:returns: command results |
| 307 |
""" |
| 308 |
|
| 309 |
if self.token is None: |
| 310 |
self.module.fail_json(msg="No authorize token") |
| 311 |
|
| 312 |
|
| 313 |
headers = { |
| 314 |
'Content-Type': 'application/json', |
| 315 |
'X-Auth-Token': self.token |
| 316 |
} |
| 317 |
|
| 318 |
max_retries = 3 |
| 319 |
attempt = 0 |
| 320 |
rest = None |
| 321 |
|
| 322 |
while attempt < max_retries: |
| 323 |
rest = self._svc_rest(method='POST', headers=headers, cmd=cmd, |
| 324 |
cmdopts=cmdopts, cmdargs=cmdargs, timeout=timeout) |
| 325 |
|
| 326 |
if rest['code'] != 429: |
| 327 |
break |
| 328 |
self.log("REST API failed with 429. Retrying... (%d/%d)", attempt + 1, max_retries) |
| 329 |
sleep(2 ** attempt) |
| 330 |
attempt += 1 |
| 331 |
return rest |
| 332 |
|
| 333 |
def svc_run_command(self, cmd, cmdopts, cmdargs, timeout=TIMEOUT): |
| 334 |
""" Generic execute a SVC command |
| 335 |
:param cmd: svc command to run |
| 336 |
:type cmd: string |
| 337 |
:param cmdopts: svc command options, name parameter and value |
| 338 |
:type cmdopts: dict |
| 339 |
:param cmdargs: svc command arguments, non-named parameters |
| 340 |
:type cmdargs: list |
| 341 |
:param timeout: open_url argument to set timeout for http gateway |
| 342 |
:type timeout: int |
| 343 |
:returns: command output |
| 344 |
""" |
| 345 |
rest = self._svc_token_wrap(cmd, cmdopts, cmdargs, timeout) |
| 346 |
self.log("svc_run_command rest=%s", rest) |
| 347 |
|
| 348 |
if rest['err']: |
| 349 |
self.log("[ERROR]: Unable to connect via REST: %s", rest['err']) |
| 350 |
unreachable = False |
| 351 |
if "Operation timed out" in rest['err']: |
| 352 |
unreachable = True |
| 353 |
self.module.exit_json(msg=rest, unreachable=unreachable) |
| 354 |
self.module.fail_json(msg=rest) |
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
return rest['out'] |
| 359 |
|
| 360 |
def svc_obj_info(self, cmd, cmdopts, cmdargs, timeout=TIMEOUT): |
| 361 |
""" Obtain information about an SVC object through the ls command |
| 362 |
:param cmd: svc command to run |
| 363 |
:type cmd: string |
| 364 |
:param cmdopts: svc command options, name parameter and value |
| 365 |
:type cmdopts: dict |
| 366 |
:param cmdargs: svc command arguments, non-named paramaters |
| 367 |
:type cmdargs: list |
| 368 |
:param timeout: open_url argument to set timeout for http gateway |
| 369 |
:type timeout: int |
| 370 |
:returns: command output |
| 371 |
:rtype: dict |
| 372 |
""" |
| 373 |
|
| 374 |
rest = self._svc_token_wrap(cmd, cmdopts, cmdargs, timeout) |
| 375 |
self.log("svc_obj_info rest=%s", rest) |
| 376 |
''' |
| 377 |
ibm_svc_info may throw following error-codes for few svc objects when objectname = all |
| 378 |
Handle those errors internally |
| 379 |
error-codes: |
| 380 |
CMMVC5707E - Required parameters are missing. |
| 381 |
CMMVC5767E - One or more of the parameters specified are invalid or a parameter is missing. |
| 382 |
CMMVC7205E - The command failed because it is not supported. |
| 383 |
''' |
| 384 |
error_codes_to_absorb = ["CMMVC5707E", "CMMVC5767E", "CMMVC7205E"] |
| 385 |
if rest['code']: |
| 386 |
if rest['code'] == 500: |
| 387 |
|
| 388 |
error_text = rest['out'].decode('utf8').split(":")[-1].strip() |
| 389 |
error_code = error_text.split(" ")[0] |
| 390 |
self.log(error_code) |
| 391 |
if error_code in error_codes_to_absorb: |
| 392 |
return error_text |
| 393 |
return None |
| 394 |
if rest['code'] == 404: |
| 395 |
return rest['code'] |
| 396 |
|
| 397 |
|
| 398 |
if rest['err']: |
| 399 |
self.log("[ERROR]: Unable to connect via REST: %s", rest['err']) |
| 400 |
unreachable = False |
| 401 |
if "Operation timed out" in rest['err']: |
| 402 |
unreachable = True |
| 403 |
self.module.exit_json(msg=rest, unreachable=unreachable) |
| 404 |
self.module.fail_json(msg=rest) |
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
return rest['out'] |
| 409 |
|
| 410 |
def get_auth_token(self): |
| 411 |
""" Obtain information about an SVC object through the ls command |
| 412 |
:returns: authentication token |
| 413 |
""" |
| 414 |
|
| 415 |
self.token = self._svc_authorize() |
| 416 |
self.log("_connect by using token") |
| 417 |
if not self.token: |
| 418 |
self.module.exit_json(msg='Failed to obtain access token', unreachable=True) |
| 419 |
|
| 420 |
return self.token |
| 421 |
|
| 422 |
def register_plugin_cmdopts(self): |
| 423 |
cmdopts = {} |
| 424 |
name = "Ansible" |
| 425 |
unique_key = self.username + "_" + str(uuid.getnode()) |
| 426 |
metadata = "" |
| 427 |
|
| 428 |
try: |
| 429 |
caller_class = inspect.stack()[3].frame.f_locals.get('self', None) |
| 430 |
caller_class_name = caller_class.__class__.__name__ |
| 431 |
module_name = str(inspect.stack()[3].filename).rsplit('/', maxsplit=1)[-1] |
| 432 |
metadata = module_name[:-3] + " module with class " + str(caller_class_name) + " has been executed by " + self.username |
| 433 |
except Exception as e: |
| 434 |
metadata = "" |
| 435 |
|
| 436 |
cmdopts['name'] = name |
| 437 |
cmdopts['uniquekey'] = unique_key |
| 438 |
cmdopts['version'] = COLLECTION_VERSION |
| 439 |
cmdopts['metadata'] = metadata |
| 440 |
return cmdopts |