| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright (c) 2019 Ansible Project |
| 3 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import decimal |
| 8 |
import json |
| 9 |
import os |
| 10 |
|
| 11 |
from ast import literal_eval |
| 12 |
from ansible.module_utils._internal import _no_six |
| 13 |
from ansible.module_utils.common import json as _common_json |
| 14 |
from ansible.module_utils.common.text.converters import to_native |
| 15 |
from ansible.module_utils.common.collections import is_iterable |
| 16 |
from ansible.module_utils.common.text.formatters import human_to_bytes |
| 17 |
from ansible.module_utils.parsing.convert_bool import boolean |
| 18 |
|
| 19 |
|
| 20 |
def count_terms(terms, parameters): |
| 21 |
"""Count the number of occurrences of a key in a given dictionary |
| 22 |
|
| 23 |
:arg terms: String or iterable of values to check |
| 24 |
:arg parameters: Dictionary of parameters |
| 25 |
|
| 26 |
:returns: An integer that is the number of occurrences of the terms values |
| 27 |
in the provided dictionary. |
| 28 |
""" |
| 29 |
|
| 30 |
if not is_iterable(terms): |
| 31 |
terms = [terms] |
| 32 |
|
| 33 |
return len(set(terms).intersection(parameters)) |
| 34 |
|
| 35 |
|
| 36 |
def check_mutually_exclusive(terms, parameters, options_context=None): |
| 37 |
"""Check mutually exclusive terms against argument parameters |
| 38 |
|
| 39 |
Accepts a single list or list of lists that are groups of terms that should be |
| 40 |
mutually exclusive with one another |
| 41 |
|
| 42 |
:arg terms: List of mutually exclusive parameters |
| 43 |
:arg parameters: Dictionary of parameters |
| 44 |
:kwarg options_context: List of strings of parent key names if ``terms`` are |
| 45 |
in a sub spec. |
| 46 |
|
| 47 |
:returns: Empty list or raises :class:`TypeError` if the check fails. |
| 48 |
""" |
| 49 |
|
| 50 |
results = [] |
| 51 |
if terms is None: |
| 52 |
return results |
| 53 |
|
| 54 |
for check in terms: |
| 55 |
count = count_terms(check, parameters) |
| 56 |
if count > 1: |
| 57 |
results.append(check) |
| 58 |
|
| 59 |
if results: |
| 60 |
full_list = ['|'.join(check) for check in results] |
| 61 |
msg = "parameters are mutually exclusive: %s" % ', '.join(full_list) |
| 62 |
if options_context: |
| 63 |
msg = "{0} found in {1}".format(msg, " -> ".join(options_context)) |
| 64 |
raise TypeError(to_native(msg)) |
| 65 |
|
| 66 |
return results |
| 67 |
|
| 68 |
|
| 69 |
def check_required_one_of(terms, parameters, options_context=None): |
| 70 |
"""Check each list of terms to ensure at least one exists in the given module |
| 71 |
parameters |
| 72 |
|
| 73 |
Accepts a list of lists or tuples |
| 74 |
|
| 75 |
:arg terms: List of lists of terms to check. For each list of terms, at |
| 76 |
least one is required. |
| 77 |
:arg parameters: Dictionary of parameters |
| 78 |
:kwarg options_context: List of strings of parent key names if ``terms`` are |
| 79 |
in a sub spec. |
| 80 |
|
| 81 |
:returns: Empty list or raises :class:`TypeError` if the check fails. |
| 82 |
""" |
| 83 |
|
| 84 |
results = [] |
| 85 |
if terms is None: |
| 86 |
return results |
| 87 |
|
| 88 |
for term in terms: |
| 89 |
count = count_terms(term, parameters) |
| 90 |
if count == 0: |
| 91 |
results.append(term) |
| 92 |
|
| 93 |
if results: |
| 94 |
for term in results: |
| 95 |
msg = "one of the following is required: %s" % ', '.join(term) |
| 96 |
if options_context: |
| 97 |
msg = "{0} found in {1}".format(msg, " -> ".join(options_context)) |
| 98 |
raise TypeError(to_native(msg)) |
| 99 |
|
| 100 |
return results |
| 101 |
|
| 102 |
|
| 103 |
def check_required_together(terms, parameters, options_context=None): |
| 104 |
"""Check each list of terms to ensure every parameter in each list exists |
| 105 |
in the given parameters. |
| 106 |
|
| 107 |
Accepts a list of lists or tuples. |
| 108 |
|
| 109 |
:arg terms: List of lists of terms to check. Each list should include |
| 110 |
parameters that are all required when at least one is specified |
| 111 |
in the parameters. |
| 112 |
:arg parameters: Dictionary of parameters |
| 113 |
:kwarg options_context: List of strings of parent key names if ``terms`` are |
| 114 |
in a sub spec. |
| 115 |
|
| 116 |
:returns: Empty list or raises :class:`TypeError` if the check fails. |
| 117 |
""" |
| 118 |
|
| 119 |
results = [] |
| 120 |
if terms is None: |
| 121 |
return results |
| 122 |
|
| 123 |
for term in terms: |
| 124 |
counts = [count_terms(field, parameters) for field in term] |
| 125 |
non_zero = [c for c in counts if c > 0] |
| 126 |
if len(non_zero) > 0: |
| 127 |
if 0 in counts: |
| 128 |
results.append(term) |
| 129 |
if results: |
| 130 |
for term in results: |
| 131 |
msg = "parameters are required together: %s" % ', '.join(term) |
| 132 |
if options_context: |
| 133 |
msg = "{0} found in {1}".format(msg, " -> ".join(options_context)) |
| 134 |
raise TypeError(to_native(msg)) |
| 135 |
|
| 136 |
return results |
| 137 |
|
| 138 |
|
| 139 |
def check_required_by(requirements, parameters, options_context=None): |
| 140 |
"""For each key in requirements, check the corresponding list to see if they |
| 141 |
exist in parameters. |
| 142 |
|
| 143 |
Accepts a single string or list of values for each key. |
| 144 |
|
| 145 |
:arg requirements: Dictionary of requirements |
| 146 |
:arg parameters: Dictionary of parameters |
| 147 |
:kwarg options_context: List of strings of parent key names if ``requirements`` are |
| 148 |
in a sub spec. |
| 149 |
|
| 150 |
:returns: Empty dictionary or raises :class:`TypeError` if the check fails. |
| 151 |
""" |
| 152 |
|
| 153 |
result = {} |
| 154 |
if requirements is None: |
| 155 |
return result |
| 156 |
|
| 157 |
for (key, value) in requirements.items(): |
| 158 |
if key not in parameters or parameters[key] is None: |
| 159 |
continue |
| 160 |
# Support strings (single-item lists) |
| 161 |
if isinstance(value, str): |
| 162 |
value = [value] |
| 163 |
|
| 164 |
if missing := [required for required in value if required not in parameters or parameters[required] is None]: |
| 165 |
msg = f"missing parameter(s) required by '{key}': {', '.join(missing)}" |
| 166 |
if options_context: |
| 167 |
msg = f"{msg} found in {' -> '.join(options_context)}" |
| 168 |
raise TypeError(to_native(msg)) |
| 169 |
return result |
| 170 |
|
| 171 |
|
| 172 |
def check_required_arguments(argument_spec, parameters, options_context=None): |
| 173 |
"""Check all parameters in argument_spec and return a list of parameters |
| 174 |
that are required but not present in parameters. |
| 175 |
|
| 176 |
Raises :class:`TypeError` if the check fails |
| 177 |
|
| 178 |
:arg argument_spec: Argument spec dictionary containing all parameters |
| 179 |
and their specification |
| 180 |
:arg parameters: Dictionary of parameters |
| 181 |
:kwarg options_context: List of strings of parent key names if ``argument_spec`` are |
| 182 |
in a sub spec. |
| 183 |
|
| 184 |
:returns: Empty list or raises :class:`TypeError` if the check fails. |
| 185 |
""" |
| 186 |
|
| 187 |
missing = [] |
| 188 |
if argument_spec is None: |
| 189 |
return missing |
| 190 |
|
| 191 |
for (k, v) in argument_spec.items(): |
| 192 |
required = v.get('required', False) |
| 193 |
if required and k not in parameters: |
| 194 |
missing.append(k) |
| 195 |
|
| 196 |
if missing: |
| 197 |
msg = "missing required arguments: %s" % ", ".join(sorted(missing)) |
| 198 |
if options_context: |
| 199 |
msg = "{0} found in {1}".format(msg, " -> ".join(options_context)) |
| 200 |
raise TypeError(to_native(msg)) |
| 201 |
|
| 202 |
return missing |
| 203 |
|
| 204 |
|
| 205 |
def check_required_if(requirements, parameters, options_context=None): |
| 206 |
"""Check parameters that are conditionally required |
| 207 |
|
| 208 |
Raises :class:`TypeError` if the check fails |
| 209 |
|
| 210 |
:arg requirements: List of lists specifying a parameter, value, parameters |
| 211 |
required when the given parameter is the specified value, and optionally |
| 212 |
a boolean indicating any or all parameters are required. |
| 213 |
|
| 214 |
:Example: |
| 215 |
|
| 216 |
.. code-block:: python |
| 217 |
|
| 218 |
required_if=[ |
| 219 |
['state', 'present', ('path',), True], |
| 220 |
['someint', 99, ('bool_param', 'string_param')], |
| 221 |
] |
| 222 |
|
| 223 |
:arg parameters: Dictionary of parameters |
| 224 |
|
| 225 |
:returns: Empty list or raises :class:`TypeError` if the check fails. |
| 226 |
The results attribute of the exception contains a list of dictionaries. |
| 227 |
Each dictionary is the result of evaluating each item in requirements. |
| 228 |
Each return dictionary contains the following keys: |
| 229 |
|
| 230 |
:key missing: List of parameters that are required but missing |
| 231 |
:key requires: 'any' or 'all' |
| 232 |
:key parameter: Parameter name that has the requirement |
| 233 |
:key value: Original value of the parameter |
| 234 |
:key requirements: Original required parameters |
| 235 |
|
| 236 |
:Example: |
| 237 |
|
| 238 |
.. code-block:: python |
| 239 |
|
| 240 |
[ |
| 241 |
{ |
| 242 |
'parameter': 'someint', |
| 243 |
'value': 99 |
| 244 |
'requirements': ('bool_param', 'string_param'), |
| 245 |
'missing': ['string_param'], |
| 246 |
'requires': 'all', |
| 247 |
} |
| 248 |
] |
| 249 |
|
| 250 |
:kwarg options_context: List of strings of parent key names if ``requirements`` are |
| 251 |
in a sub spec. |
| 252 |
""" |
| 253 |
results = [] |
| 254 |
if requirements is None: |
| 255 |
return results |
| 256 |
|
| 257 |
for req in requirements: |
| 258 |
missing = {} |
| 259 |
missing['missing'] = [] |
| 260 |
max_missing_count = 0 |
| 261 |
is_one_of = False |
| 262 |
if len(req) == 4: |
| 263 |
key, val, requirements, is_one_of = req |
| 264 |
else: |
| 265 |
key, val, requirements = req |
| 266 |
|
| 267 |
# is_one_of is True at least one requirement should be |
| 268 |
# present, else all requirements should be present. |
| 269 |
if is_one_of: |
| 270 |
max_missing_count = len(requirements) |
| 271 |
missing['requires'] = 'any' |
| 272 |
else: |
| 273 |
missing['requires'] = 'all' |
| 274 |
|
| 275 |
if key in parameters and parameters[key] == val: |
| 276 |
for check in requirements: |
| 277 |
count = count_terms(check, parameters) |
| 278 |
if count == 0: |
| 279 |
missing['missing'].append(check) |
| 280 |
if len(missing['missing']) and len(missing['missing']) >= max_missing_count: |
| 281 |
missing['parameter'] = key |
| 282 |
missing['value'] = val |
| 283 |
missing['requirements'] = requirements |
| 284 |
results.append(missing) |
| 285 |
|
| 286 |
if results: |
| 287 |
for missing in results: |
| 288 |
msg = "%s is %s but %s of the following are missing: %s" % ( |
| 289 |
missing['parameter'], missing['value'], missing['requires'], ', '.join(missing['missing'])) |
| 290 |
if options_context: |
| 291 |
msg = "{0} found in {1}".format(msg, " -> ".join(options_context)) |
| 292 |
raise TypeError(to_native(msg)) |
| 293 |
|
| 294 |
return results |
| 295 |
|
| 296 |
|
| 297 |
def check_missing_parameters(parameters, required_parameters=None): |
| 298 |
"""This is for checking for required params when we can not check via |
| 299 |
argspec because we need more information than is simply given in the argspec. |
| 300 |
|
| 301 |
Raises :class:`TypeError` if any required parameters are missing |
| 302 |
|
| 303 |
:arg parameters: Dictionary of parameters |
| 304 |
:arg required_parameters: List of parameters to look for in the given parameters. |
| 305 |
|
| 306 |
:returns: Empty list or raises :class:`TypeError` if the check fails. |
| 307 |
""" |
| 308 |
missing_params = [] |
| 309 |
if required_parameters is None: |
| 310 |
return missing_params |
| 311 |
|
| 312 |
for param in required_parameters: |
| 313 |
if not parameters.get(param): |
| 314 |
missing_params.append(param) |
| 315 |
|
| 316 |
if missing_params: |
| 317 |
msg = "missing required arguments: %s" % ', '.join(missing_params) |
| 318 |
raise TypeError(to_native(msg)) |
| 319 |
|
| 320 |
return missing_params |
| 321 |
|
| 322 |
|
| 323 |
# FIXME: The param and prefix parameters here are coming from AnsibleModule._check_type_string() |
| 324 |
# which is using those for the warning messaged based on string conversion warning settings. |
| 325 |
# Not sure how to deal with that here since we don't have config state to query. |
| 326 |
def check_type_str(value, allow_conversion=True, param=None, prefix=''): |
| 327 |
"""Verify that the value is a string or convert to a string. |
| 328 |
|
| 329 |
Since unexpected changes can sometimes happen when converting to a string, |
| 330 |
``allow_conversion`` controls whether or not the value will be converted or a |
| 331 |
TypeError will be raised if the value is not a string and would be converted |
| 332 |
|
| 333 |
:arg value: Value to validate or convert to a string |
| 334 |
:arg allow_conversion: Whether to convert the string and return it or raise |
| 335 |
a TypeError |
| 336 |
|
| 337 |
:returns: Original value if it is a string, the value converted to a string |
| 338 |
if allow_conversion=True, or raises a TypeError if allow_conversion=False. |
| 339 |
""" |
| 340 |
if isinstance(value, str): |
| 341 |
return value |
| 342 |
|
| 343 |
if value is None: |
| 344 |
return '' # approximate pre-2.19 templating None->empty str equivalency here for backward compatibility |
| 345 |
|
| 346 |
if allow_conversion: |
| 347 |
return to_native(value, errors='surrogate_or_strict') |
| 348 |
|
| 349 |
msg = "'{0!r}' is not a string and conversion is not allowed".format(value) |
| 350 |
raise TypeError(to_native(msg)) |
| 351 |
|
| 352 |
|
| 353 |
def _check_type_str_no_conversion(value) -> str: |
| 354 |
return check_type_str(value, allow_conversion=False) |
| 355 |
|
| 356 |
|
| 357 |
def check_type_list(value): |
| 358 |
"""Verify that the value is a list or convert to a list |
| 359 |
|
| 360 |
A comma separated string will be split into a list. Raises a :class:`TypeError` |
| 361 |
if unable to convert to a list. |
| 362 |
|
| 363 |
:arg value: Value to validate or convert to a list |
| 364 |
|
| 365 |
:returns: Original value if it is already a list, single item list if a |
| 366 |
float, int, or string without commas, or a multi-item list if a |
| 367 |
comma-delimited string. |
| 368 |
""" |
| 369 |
if isinstance(value, list): |
| 370 |
return value |
| 371 |
|
| 372 |
# DTFIX-FUTURE: deprecate legacy comma split functionality, eventually replace with `_check_type_list_strict` |
| 373 |
if isinstance(value, str): |
| 374 |
return value.split(",") |
| 375 |
elif isinstance(value, int) or isinstance(value, float): |
| 376 |
return [str(value)] |
| 377 |
|
| 378 |
raise TypeError('%s cannot be converted to a list' % type(value)) |
| 379 |
|
| 380 |
|
| 381 |
def _check_type_list_strict(value): |
| 382 |
# FUTURE: this impl should replace `check_type_list` |
| 383 |
if isinstance(value, list): |
| 384 |
return value |
| 385 |
|
| 386 |
return [value] |
| 387 |
|
| 388 |
|
| 389 |
def check_type_dict(value): |
| 390 |
"""Verify that value is a dict or convert it to a dict and return it. |
| 391 |
|
| 392 |
Raises :class:`TypeError` if unable to convert to a dict |
| 393 |
|
| 394 |
:arg value: Dict or string to convert to a dict. Accepts ``k1=v2, k2=v2`` or ``k1=v2 k2=v2``. |
| 395 |
|
| 396 |
:returns: value converted to a dictionary |
| 397 |
""" |
| 398 |
if isinstance(value, dict): |
| 399 |
return value |
| 400 |
|
| 401 |
if isinstance(value, str): |
| 402 |
if value.startswith("{"): |
| 403 |
try: |
| 404 |
return json.loads(value) |
| 405 |
except Exception: |
| 406 |
try: |
| 407 |
result = literal_eval(value) |
| 408 |
except Exception: |
| 409 |
pass |
| 410 |
else: |
| 411 |
if isinstance(result, dict): |
| 412 |
return result |
| 413 |
raise TypeError('unable to evaluate string as dictionary') |
| 414 |
elif '=' in value: |
| 415 |
fields = [] |
| 416 |
field_buffer = [] |
| 417 |
in_quote = False |
| 418 |
in_escape = False |
| 419 |
for c in value.strip(): |
| 420 |
if in_escape: |
| 421 |
field_buffer.append(c) |
| 422 |
in_escape = False |
| 423 |
elif c == '\\': |
| 424 |
in_escape = True |
| 425 |
elif not in_quote and c in ('\'', '"'): |
| 426 |
in_quote = c |
| 427 |
elif in_quote and in_quote == c: |
| 428 |
in_quote = False |
| 429 |
elif not in_quote and c in (',', ' '): |
| 430 |
field = ''.join(field_buffer) |
| 431 |
if field: |
| 432 |
fields.append(field) |
| 433 |
field_buffer = [] |
| 434 |
else: |
| 435 |
field_buffer.append(c) |
| 436 |
|
| 437 |
field = ''.join(field_buffer) |
| 438 |
if field: |
| 439 |
fields.append(field) |
| 440 |
try: |
| 441 |
return dict(x.split("=", 1) for x in fields) |
| 442 |
except ValueError: |
| 443 |
# no "=" to split on: "k1=v1, k2" |
| 444 |
raise TypeError('unable to evaluate string in the "key=value" format as dictionary') |
| 445 |
else: |
| 446 |
raise TypeError("dictionary requested, could not parse JSON or key=value") |
| 447 |
|
| 448 |
raise TypeError('%s cannot be converted to a dict' % type(value)) |
| 449 |
|
| 450 |
|
| 451 |
def check_type_bool(value): |
| 452 |
"""Verify that the value is a bool or convert it to a bool and return it. |
| 453 |
|
| 454 |
Raises :class:`TypeError` if unable to convert to a bool |
| 455 |
|
| 456 |
:arg value: String, int, or float to convert to bool. Valid booleans include: |
| 457 |
'1', 'on', 1, '0', 0, 'n', 'f', 'false', 'true', 'y', 't', 'yes', 'no', 'off' |
| 458 |
|
| 459 |
:returns: Boolean True or False |
| 460 |
""" |
| 461 |
if isinstance(value, bool): |
| 462 |
return value |
| 463 |
|
| 464 |
if isinstance(value, str) or isinstance(value, (int, float)): |
| 465 |
return boolean(value) |
| 466 |
|
| 467 |
raise TypeError('%s cannot be converted to a bool' % type(value)) |
| 468 |
|
| 469 |
|
| 470 |
def check_type_int(value): |
| 471 |
"""Verify that the value is an integer and return it or convert the value |
| 472 |
to an integer and return it |
| 473 |
|
| 474 |
Raises :class:`TypeError` if unable to convert to an int |
| 475 |
|
| 476 |
:arg value: String or int to convert of verify |
| 477 |
|
| 478 |
:return: int of given value |
| 479 |
""" |
| 480 |
if not isinstance(value, int): |
| 481 |
try: |
| 482 |
if (decimal_value := decimal.Decimal(value)) != (int_value := int(decimal_value)): |
| 483 |
raise ValueError("Significant decimal part found") |
| 484 |
else: |
| 485 |
value = int_value |
| 486 |
except (ArithmeticError, TypeError, ValueError) as e: |
| 487 |
raise TypeError(f'"{value!r}" cannot be converted to an int') from e |
| 488 |
return value |
| 489 |
|
| 490 |
|
| 491 |
def check_type_float(value): |
| 492 |
"""Verify that value is a float or convert it to a float and return it |
| 493 |
|
| 494 |
Raises :class:`TypeError` if unable to convert to a float |
| 495 |
|
| 496 |
:arg value: float, int, str, or bytes to verify or convert and return. |
| 497 |
|
| 498 |
:returns: float of given value. |
| 499 |
""" |
| 500 |
if not isinstance(value, float): |
| 501 |
try: |
| 502 |
value = float(value) |
| 503 |
except (TypeError, ValueError) as e: |
| 504 |
raise TypeError(f'{type(value)} cannot be converted to a float') |
| 505 |
return value |
| 506 |
|
| 507 |
|
| 508 |
def check_type_path(value,): |
| 509 |
"""Verify the provided value is a string or convert it to a string, |
| 510 |
then return the expanded path |
| 511 |
""" |
| 512 |
value = check_type_str(value) |
| 513 |
return os.path.expanduser(os.path.expandvars(value)) |
| 514 |
|
| 515 |
|
| 516 |
def check_type_raw(value): |
| 517 |
"""Returns the raw value""" |
| 518 |
return value |
| 519 |
|
| 520 |
|
| 521 |
def check_type_bytes(value): |
| 522 |
"""Convert a human-readable string value to bytes |
| 523 |
|
| 524 |
Raises :class:`TypeError` if unable to convert the value |
| 525 |
""" |
| 526 |
try: |
| 527 |
return human_to_bytes(value) |
| 528 |
except ValueError: |
| 529 |
raise TypeError('%s cannot be converted to a Byte value' % type(value)) |
| 530 |
|
| 531 |
|
| 532 |
def check_type_bits(value): |
| 533 |
"""Convert a human-readable string bits value to bits in integer. |
| 534 |
|
| 535 |
Example: ``check_type_bits('1Mb')`` returns integer 1048576. |
| 536 |
|
| 537 |
Raises :class:`TypeError` if unable to convert the value. |
| 538 |
""" |
| 539 |
try: |
| 540 |
return human_to_bytes(value, isbits=True) |
| 541 |
except ValueError: |
| 542 |
raise TypeError('%s cannot be converted to a Bit value' % type(value)) |
| 543 |
|
| 544 |
|
| 545 |
def check_type_jsonarg(value): |
| 546 |
""" |
| 547 |
JSON serialize dict/list/tuple, strip str and bytes. |
| 548 |
Previously required for cases where Ansible/Jinja classic-mode literal eval pass could inadvertently deserialize objects. |
| 549 |
""" |
| 550 |
# deprecated: description='deprecate jsonarg type support' core_version='2.23' |
| 551 |
# deprecate( |
| 552 |
# msg="The `jsonarg` type is deprecated.", |
| 553 |
# version="2.27", |
| 554 |
# help_text="JSON string arguments should use `str`; structures can be explicitly serialized as JSON with the `to_json` filter.", |
| 555 |
# ) |
| 556 |
|
| 557 |
if isinstance(value, (str, bytes)): |
| 558 |
return value.strip() |
| 559 |
|
| 560 |
if isinstance(value, (list, tuple, dict)): |
| 561 |
return json.dumps(value, cls=_common_json._get_legacy_encoder(), _decode_bytes=True) |
| 562 |
|
| 563 |
raise TypeError('%s cannot be converted to a json string' % type(value)) |
| 564 |
|
| 565 |
|
| 566 |
def __getattr__(importable_name): |
| 567 |
return _no_six.deprecate(importable_name, __name__, "string_types") |