| 1 |
# This code is part of Ansible, but is an independent component. |
| 2 |
# This particular file snippet, and this file snippet only, is BSD licensed. |
| 3 |
# Modules you write using this snippet, which is embedded dynamically by Ansible |
| 4 |
# still belong to the author of the module, and may assign their own license |
| 5 |
# to the complete work. |
| 6 |
# |
| 7 |
# Copyright (c) 2018, Laurent Nicolas <[email protected]> |
| 8 |
# All rights reserved. |
| 9 |
# |
| 10 |
# Redistribution and use in source and binary forms, with or without modification, |
| 11 |
# are permitted provided that the following conditions are met: |
| 12 |
# |
| 13 |
# * Redistributions of source code must retain the above copyright |
| 14 |
# notice, this list of conditions and the following disclaimer. |
| 15 |
# * Redistributions in binary form must reproduce the above copyright notice, |
| 16 |
# this list of conditions and the following disclaimer in the documentation |
| 17 |
# and/or other materials provided with the distribution. |
| 18 |
# |
| 19 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 20 |
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 21 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 22 |
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 23 |
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 24 |
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| 26 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE |
| 27 |
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 |
|
| 29 |
''' Support class for NetApp ansible modules ''' |
| 30 |
|
| 31 |
from __future__ import (absolute_import, division, print_function) |
| 32 |
__metaclass__ = type |
| 33 |
|
| 34 |
from copy import deepcopy |
| 35 |
import re |
| 36 |
import traceback |
| 37 |
import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils |
| 38 |
|
| 39 |
ZAPI_ONLY_DEPRECATION_MESSAGE = "This module only supports ZAPI and is deprecated. "\ |
| 40 |
"After upgrading to ONTAP 9.14 and beyond, ONTAPI (ZAPI) remains active for 30 days. "\ |
| 41 |
"If no calls are detected, it will be automatically disabled but can be re-enabled via CLI command." |
| 42 |
|
| 43 |
|
| 44 |
def cmp(obj1, obj2): |
| 45 |
""" |
| 46 |
Python 3 does not have a cmp function, this will do the cmp. |
| 47 |
:param obj1: first object to check |
| 48 |
:param obj2: second object to check |
| 49 |
:return: |
| 50 |
""" |
| 51 |
# convert to lower case for string comparison. |
| 52 |
if obj1 is None: |
| 53 |
return -1 |
| 54 |
if isinstance(obj1, str) and isinstance(obj2, str): |
| 55 |
obj1 = obj1.lower() |
| 56 |
obj2 = obj2.lower() |
| 57 |
# if list has string element, convert string to lower case. |
| 58 |
if isinstance(obj1, list) and isinstance(obj2, list): |
| 59 |
obj1 = [x.lower() if isinstance(x, str) else x for x in obj1] |
| 60 |
obj2 = [x.lower() if isinstance(x, str) else x for x in obj2] |
| 61 |
obj1.sort() |
| 62 |
obj2.sort() |
| 63 |
return (obj1 > obj2) - (obj1 < obj2) |
| 64 |
|
| 65 |
|
| 66 |
class NetAppModule(object): |
| 67 |
''' |
| 68 |
Common class for NetApp modules |
| 69 |
set of support functions to derive actions based |
| 70 |
on the current state of the system, and a desired state |
| 71 |
''' |
| 72 |
|
| 73 |
def __init__(self, module=None): |
| 74 |
# we can call this with module set to self or self.module |
| 75 |
# self is a NetApp module, while self.module is the AnsibleModule object |
| 76 |
self.netapp_module = None |
| 77 |
self.ansible_module = module |
| 78 |
if module and getattr(module, 'module', None) is not None: |
| 79 |
self.netapp_module = module |
| 80 |
self.ansible_module = module.module |
| 81 |
# When using self or self.module, this gives access to: |
| 82 |
# self.ansible_module.fail_json |
| 83 |
# When using self, this gives access to: |
| 84 |
# self.netapp_module.rest_api.log_debug |
| 85 |
self.log = [] |
| 86 |
self.changed = False |
| 87 |
self.parameters = {'name': 'not initialized'} |
| 88 |
self.zapi_string_keys = {} |
| 89 |
self.zapi_bool_keys = {} |
| 90 |
self.zapi_list_keys = {} |
| 91 |
self.zapi_int_keys = {} |
| 92 |
self.zapi_required = {} |
| 93 |
self.params_to_rest_api_keys = {} |
| 94 |
|
| 95 |
def module_deprecated(self, module): |
| 96 |
module.warn(ZAPI_ONLY_DEPRECATION_MESSAGE) |
| 97 |
|
| 98 |
def module_replaces(self, new_module, module): |
| 99 |
self.module_deprecated(module) |
| 100 |
module.warn('netapp.ontap.%s should be used instead.' % new_module) |
| 101 |
|
| 102 |
def set_parameters(self, ansible_params): |
| 103 |
self.parameters = {} |
| 104 |
for param in ansible_params: |
| 105 |
if ansible_params[param] is not None: |
| 106 |
self.parameters[param] = ansible_params[param] |
| 107 |
return self.parameters |
| 108 |
|
| 109 |
def fall_back_to_zapi(self, module, msg, parameters): |
| 110 |
if parameters['use_rest'].lower() == 'always': |
| 111 |
module.fail_json(msg='Error: %s' % msg) |
| 112 |
if parameters['use_rest'].lower() == 'auto': |
| 113 |
module.warn('Falling back to ZAPI: %s' % msg) |
| 114 |
return False |
| 115 |
|
| 116 |
def check_and_set_parameters(self, module): |
| 117 |
self.parameters = {} |
| 118 |
check_for_none = netapp_utils.has_feature(module, 'check_required_params_for_none') |
| 119 |
if check_for_none: |
| 120 |
required_keys = [key for key, value in module.argument_spec.items() if value.get('required')] |
| 121 |
for param in module.params: |
| 122 |
if module.params[param] is not None: |
| 123 |
self.parameters[param] = module.params[param] |
| 124 |
elif check_for_none and param in required_keys: |
| 125 |
module.fail_json(msg="%s requires a value, got: None" % param) |
| 126 |
return self.parameters |
| 127 |
|
| 128 |
@staticmethod |
| 129 |
def type_error_message(type_str, key, value): |
| 130 |
return "expecting '%s' type for %s: %s, got: %s" % (type_str, repr(key), repr(value), type(value)) |
| 131 |
|
| 132 |
def get_value_for_bool(self, from_zapi, value, key=None): |
| 133 |
""" |
| 134 |
Convert boolean values to string or vice-versa |
| 135 |
If from_zapi = True, value is converted from string (as it appears in ZAPI) to boolean |
| 136 |
If from_zapi = False, value is converted from boolean to string |
| 137 |
For get() method, from_zapi = True |
| 138 |
For modify(), create(), from_zapi = False |
| 139 |
:param from_zapi: convert the value from ZAPI or to ZAPI acceptable type |
| 140 |
:param value: value of the boolean attribute |
| 141 |
:param key: if present, force error checking to validate type, and accepted values |
| 142 |
:return: string or boolean |
| 143 |
""" |
| 144 |
if value is None: |
| 145 |
return None |
| 146 |
if from_zapi: |
| 147 |
if key is not None and not isinstance(value, str): |
| 148 |
raise TypeError(self.type_error_message('str', key, value)) |
| 149 |
if key is not None and value not in ('true', 'false'): |
| 150 |
raise ValueError('Unexpected value: %s received from ZAPI for boolean attribute: %s' % (repr(value), repr(key))) |
| 151 |
return value == 'true' |
| 152 |
if key is not None and not isinstance(value, bool): |
| 153 |
raise TypeError(self.type_error_message('bool', key, value)) |
| 154 |
return 'true' if value else 'false' |
| 155 |
|
| 156 |
def get_value_for_int(self, from_zapi, value, key=None): |
| 157 |
""" |
| 158 |
Convert integer values to string or vice-versa |
| 159 |
If from_zapi = True, value is converted from string (as it appears in ZAPI) to integer |
| 160 |
If from_zapi = False, value is converted from integer to string |
| 161 |
For get() method, from_zapi = True |
| 162 |
For modify(), create(), from_zapi = False |
| 163 |
:param from_zapi: convert the value from ZAPI or to ZAPI acceptable type |
| 164 |
:param value: value of the integer attribute |
| 165 |
:param key: if present, force error checking to validate type |
| 166 |
:return: string or integer |
| 167 |
""" |
| 168 |
if value is None: |
| 169 |
return None |
| 170 |
if from_zapi: |
| 171 |
if key is not None and not isinstance(value, str): |
| 172 |
raise TypeError(self.type_error_message('str', key, value)) |
| 173 |
return int(value) |
| 174 |
if key is not None and not isinstance(value, int): |
| 175 |
raise TypeError(self.type_error_message('int', key, value)) |
| 176 |
return str(value) |
| 177 |
|
| 178 |
def get_value_for_list(self, from_zapi, zapi_parent, zapi_child=None, data=None): |
| 179 |
""" |
| 180 |
Convert a python list() to NaElement or vice-versa |
| 181 |
If from_zapi = True, value is converted from NaElement (parent-children structure) to list() |
| 182 |
If from_zapi = False, value is converted from list() to NaElement |
| 183 |
:param zapi_parent: ZAPI parent key or the ZAPI parent NaElement |
| 184 |
:param zapi_child: ZAPI child key |
| 185 |
:param data: list() to be converted to NaElement parent-children object |
| 186 |
:param from_zapi: convert the value from ZAPI or to ZAPI acceptable type |
| 187 |
:return: list() or NaElement |
| 188 |
""" |
| 189 |
if from_zapi: |
| 190 |
if zapi_parent is None: |
| 191 |
return [] |
| 192 |
return [zapi_child.get_content() for zapi_child in zapi_parent.get_children()] |
| 193 |
|
| 194 |
zapi_parent = netapp_utils.zapi.NaElement(zapi_parent) |
| 195 |
for item in data: |
| 196 |
zapi_parent.add_new_child(zapi_child, item) |
| 197 |
return zapi_parent |
| 198 |
|
| 199 |
def get_cd_action(self, current, desired): |
| 200 |
''' takes a desired state and a current state, and return an action: |
| 201 |
create, delete, None |
| 202 |
eg: |
| 203 |
is_present = 'absent' |
| 204 |
some_object = self.get_object(source) |
| 205 |
if some_object is not None: |
| 206 |
is_present = 'present' |
| 207 |
action = cd_action(current=is_present, desired = self.desired.state()) |
| 208 |
''' |
| 209 |
desired_state = desired['state'] if 'state' in desired else 'present' |
| 210 |
if current is None and desired_state == 'absent': |
| 211 |
return None |
| 212 |
if current is not None and desired_state == 'present': |
| 213 |
return None |
| 214 |
# change in state |
| 215 |
self.changed = True |
| 216 |
return 'create' if current is None else 'delete' |
| 217 |
|
| 218 |
@staticmethod |
| 219 |
def check_keys(current, desired): |
| 220 |
''' TODO: raise an error if keys do not match |
| 221 |
with the exception of: |
| 222 |
new_name, state in desired |
| 223 |
''' |
| 224 |
|
| 225 |
@staticmethod |
| 226 |
def compare_lists(current, desired, get_list_diff): |
| 227 |
''' compares two lists and return a list of elements that are either the desired elements or elements that are |
| 228 |
modified from the current state depending on the get_list_diff flag |
| 229 |
:param: current: current item attribute in ONTAP |
| 230 |
:param: desired: attributes from playbook |
| 231 |
:param: get_list_diff: specifies whether to have a diff of desired list w.r.t current list for an attribute |
| 232 |
:return: list of attributes to be modified |
| 233 |
:rtype: list |
| 234 |
''' |
| 235 |
current_copy = deepcopy(current) |
| 236 |
desired_copy = deepcopy(desired) |
| 237 |
|
| 238 |
# get what in desired and not in current |
| 239 |
desired_diff_list = [] |
| 240 |
for item in desired: |
| 241 |
if item in current_copy: |
| 242 |
current_copy.remove(item) |
| 243 |
else: |
| 244 |
desired_diff_list.append(item) |
| 245 |
|
| 246 |
# get what in current but not in desired |
| 247 |
current_diff_list = [] |
| 248 |
for item in current: |
| 249 |
if item in desired_copy: |
| 250 |
desired_copy.remove(item) |
| 251 |
else: |
| 252 |
current_diff_list.append(item) |
| 253 |
|
| 254 |
if desired_diff_list or current_diff_list: |
| 255 |
# there are changes |
| 256 |
return desired_diff_list if get_list_diff else desired |
| 257 |
else: |
| 258 |
return None |
| 259 |
|
| 260 |
def get_modified_attributes(self, current, desired, get_list_diff=False): |
| 261 |
''' takes two dicts of attributes and return a dict of attributes that are |
| 262 |
not in the current state |
| 263 |
It is expected that all attributes of interest are listed in current and |
| 264 |
desired. |
| 265 |
:param: current: current attributes in ONTAP |
| 266 |
:param: desired: attributes from playbook |
| 267 |
:param: get_list_diff: specifies whether to have a diff of desired list w.r.t current list for an attribute |
| 268 |
:return: dict of attributes to be modified |
| 269 |
:rtype: dict |
| 270 |
|
| 271 |
NOTE: depending on the attribute, the caller may need to do a modify or a |
| 272 |
different operation (eg move volume if the modified attribute is an |
| 273 |
aggregate name) |
| 274 |
''' |
| 275 |
# if the object does not exist, we can't modify it |
| 276 |
modified = {} |
| 277 |
if current is None: |
| 278 |
return modified |
| 279 |
|
| 280 |
if not isinstance(desired, dict): |
| 281 |
raise TypeError("Expecting dict, got: %s with current: %s" % (desired, current)) |
| 282 |
# error out if keys do not match |
| 283 |
self.check_keys(current, desired) |
| 284 |
|
| 285 |
# collect changed attributes |
| 286 |
for key, value in current.items(): |
| 287 |
# if self.netapp_module: |
| 288 |
# self.netapp_module.rest_api.log_debug('KDV', "%s:%s:%s" % (key, desired.get(key), value)) |
| 289 |
if desired.get(key) is not None: |
| 290 |
modified_value = None |
| 291 |
if isinstance(value, list): |
| 292 |
modified_value = self.compare_lists(value, desired[key], get_list_diff) # get modified list from current and desired |
| 293 |
elif isinstance(value, dict): |
| 294 |
modified_value = self.get_modified_attributes(value, desired[key]) or None |
| 295 |
else: |
| 296 |
try: |
| 297 |
result = cmp(value, desired[key]) |
| 298 |
except TypeError as exc: |
| 299 |
raise TypeError("%s, key: %s, value: %s, desired: %s" % (repr(exc), key, repr(value), repr(desired[key]))) |
| 300 |
# if self.netapp_module: |
| 301 |
# self.netapp_module.rest_api.log_debug('RESULT', result) |
| 302 |
if result != 0: |
| 303 |
modified_value = desired[key] |
| 304 |
if modified_value is not None: |
| 305 |
modified[key] = modified_value |
| 306 |
|
| 307 |
if modified: |
| 308 |
self.changed = True |
| 309 |
return modified |
| 310 |
|
| 311 |
def is_rename_action(self, source, target): |
| 312 |
''' takes a source and target object, and returns True |
| 313 |
if a rename is required |
| 314 |
eg: |
| 315 |
source = self.get_object(source_name) |
| 316 |
target = self.get_object(target_name) |
| 317 |
action = is_rename_action(source, target) |
| 318 |
:return: None for error, True for rename action, False otherwise |
| 319 |
|
| 320 |
I'm not sure we need this function any more. |
| 321 |
I think a better way to do it is to: |
| 322 |
1. look if a create is required (eg the target resource does not exist and state==present) |
| 323 |
2. consider that a create can be fullfilled by different actions: rename, create from scratch, move, ... |
| 324 |
So for rename: |
| 325 |
cd_action = self.na_helper.get_cd_action(current, self.parameters) |
| 326 |
if cd_action == 'create' and self.parameters.get('from_name'): |
| 327 |
# creating new subnet by renaming |
| 328 |
current = self.get_subnet(self.parameters['from_name']) |
| 329 |
if current is None: |
| 330 |
self.module.fail_json(msg="Error renaming: subnet %s does not exist" % |
| 331 |
self.parameters['from_name']) |
| 332 |
rename = True |
| 333 |
cd_action = None |
| 334 |
''' |
| 335 |
if source is None and target is None: |
| 336 |
# error, do nothing |
| 337 |
# cannot rename a non existent resource |
| 338 |
return None |
| 339 |
if target is None: |
| 340 |
# source is not None and target is None: |
| 341 |
# rename is in order |
| 342 |
self.changed = True |
| 343 |
return True |
| 344 |
# target is not None, so do nothing as the destination exists |
| 345 |
# if source is None, maybe we already renamed |
| 346 |
# if source is not None, maybe a new resource was created after being renamed |
| 347 |
return False |
| 348 |
|
| 349 |
@staticmethod |
| 350 |
def sanitize_wwn(initiator): |
| 351 |
''' igroup initiator may or may not be using WWN format: eg 20:00:00:25:B5:00:20:01 |
| 352 |
if format is matched, convert initiator to lowercase, as this is what ONTAP is using ''' |
| 353 |
wwn_format = r'[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){7}' |
| 354 |
initiator = initiator.strip() |
| 355 |
if re.match(wwn_format, initiator): |
| 356 |
initiator = initiator.lower() |
| 357 |
return initiator |
| 358 |
|
| 359 |
def safe_get(self, an_object, key_list, allow_sparse_dict=True): |
| 360 |
''' recursively traverse a dictionary or a any object supporting get_item or indexing |
| 361 |
(in our case, python dicts and NAElement responses, and lists) |
| 362 |
It is expected that some keys can be missing, this is controlled with allow_sparse_dict |
| 363 |
|
| 364 |
return value if the key chain is exhausted |
| 365 |
return None if a key is not found and allow_sparse_dict is True |
| 366 |
raise KeyError is a key is not found and allow_sparse_dict is False (looking for exact match) |
| 367 |
raise TypeError if an intermediate element cannot be indexed, |
| 368 |
unless the element is None and allow_sparse_dict is True |
| 369 |
''' |
| 370 |
if not key_list: |
| 371 |
# we've exhausted the keys, good! |
| 372 |
return an_object |
| 373 |
key_list = list(key_list) # preserve original values |
| 374 |
key = key_list.pop(0) |
| 375 |
try: |
| 376 |
return self.safe_get(an_object[key], key_list, allow_sparse_dict=allow_sparse_dict) |
| 377 |
except (KeyError, IndexError) as exc: |
| 378 |
# error, key or index not found |
| 379 |
if allow_sparse_dict: |
| 380 |
return None |
| 381 |
raise exc |
| 382 |
except TypeError as exc: |
| 383 |
# error, we were expecting a dict or NAElement |
| 384 |
if allow_sparse_dict and an_object is None: |
| 385 |
return None |
| 386 |
raise exc |
| 387 |
|
| 388 |
def convert_value(self, value, convert_to): |
| 389 |
if convert_to is None: |
| 390 |
return value, None |
| 391 |
if not isinstance(value, str): |
| 392 |
return None, ('Unexpected type: %s for %s' % (type(value), str(value))) |
| 393 |
if convert_to == str: |
| 394 |
return value, None |
| 395 |
if convert_to == int: |
| 396 |
try: |
| 397 |
return int(value), None |
| 398 |
except ValueError as exc: |
| 399 |
return None, ('Unexpected value for int: %s, %s' % (str(value), str(exc))) |
| 400 |
if convert_to == bool: |
| 401 |
if value not in ('true', 'false'): |
| 402 |
return None, 'Unexpected value: %s received from ZAPI for boolean attribute' % value |
| 403 |
return value == 'true', None |
| 404 |
if convert_to == 'bool_online': |
| 405 |
return value == 'online', None |
| 406 |
self.ansible_module.fail_json(msg='Error: Unexpected value for convert_to: %s' % convert_to) |
| 407 |
|
| 408 |
def zapi_get_value(self, na_element, key_list, required=False, default=None, convert_to=None): |
| 409 |
""" read a value from na_element using key_list |
| 410 |
|
| 411 |
If required is True, an error is reported if a key in key_list is not found. |
| 412 |
If required is False and the value is not found, uses default as the value. |
| 413 |
If convert_to is set to str, bool, int, the ZAPI value is converted from str to the desired type. |
| 414 |
suported values: None, the python types int, str, bool, special 'bool_online' |
| 415 |
|
| 416 |
Errors: fail_json is called for: |
| 417 |
- a key is not found and required=True, |
| 418 |
- a format conversion error |
| 419 |
""" |
| 420 |
|
| 421 |
# keep a copy, as the list is mutated |
| 422 |
saved_key_list = list(key_list) |
| 423 |
try: |
| 424 |
value = self.safe_get(na_element, key_list, allow_sparse_dict=not required) |
| 425 |
except (KeyError, TypeError) as exc: |
| 426 |
error = exc |
| 427 |
else: |
| 428 |
value, error = self.convert_value(value, convert_to) if value is not None else (default, None) |
| 429 |
if error: |
| 430 |
self.ansible_module.fail_json(msg='Error reading %s from %s: %s' % (saved_key_list, na_element.to_string(), error)) |
| 431 |
return value |
| 432 |
|
| 433 |
def zapi_get_attrs(self, na_element, attr_dict, result): |
| 434 |
""" Retrieve a list of attributes from na_elements |
| 435 |
see na_ontap_volume for an example. |
| 436 |
na_element: xml element as returned by ZAPI. |
| 437 |
attr_dict: |
| 438 |
A dict of dict, with format: |
| 439 |
key: dict(key_list, required=False, default=None, convert_to=None, omitnone=False) |
| 440 |
The keys are used to index a result dictionary, values are read from a ZAPI object indexed by key_list. |
| 441 |
If required is True, an error is reported if a key in key_list is not found. |
| 442 |
If required is False and the value is not found, uses default as the value. |
| 443 |
If convert_to is set to str, bool, int, the ZAPI value is converted from str to the desired type. |
| 444 |
I'm not sure there is much value in omitnone, but it preserves backward compatibility. |
| 445 |
When the value is None, if omitnone is False, a None value is recorded, if True, the key is not set. |
| 446 |
result: an existing dictionary. keys are added or updated based on attrs. |
| 447 |
|
| 448 |
Errors: fail_json is called for: |
| 449 |
- a key is not found and required=True, |
| 450 |
- a format conversion error |
| 451 |
""" |
| 452 |
for key, kwargs in attr_dict.items(): |
| 453 |
omitnone = kwargs.pop('omitnone', False) |
| 454 |
value = self.zapi_get_value(na_element, **kwargs) |
| 455 |
if value is not None or not omitnone: |
| 456 |
result[key] = value |
| 457 |
|
| 458 |
def _filter_out_none_entries_from_dict(self, adict, allow_empty_list_or_dict): |
| 459 |
"""take a dict as input and return a dict without keys whose values are None |
| 460 |
return empty dicts or lists if allow_empty_list_or_dict otherwise skip empty dicts or lists. |
| 461 |
""" |
| 462 |
result = {} |
| 463 |
for key, value in adict.items(): |
| 464 |
if isinstance(value, (list, dict)): |
| 465 |
sub = self.filter_out_none_entries(value, allow_empty_list_or_dict) |
| 466 |
if sub or allow_empty_list_or_dict: |
| 467 |
# allow empty dict or list if allow_empty_list_or_dict is set. |
| 468 |
# skip empty dict or list otherwise |
| 469 |
result[key] = sub |
| 470 |
elif value is not None: |
| 471 |
# skip None value |
| 472 |
result[key] = value |
| 473 |
return result |
| 474 |
|
| 475 |
def _filter_out_none_entries_from_list(self, alist, allow_empty_list_or_dict): |
| 476 |
"""take a list as input and return a list without elements whose values are None |
| 477 |
return empty dicts or lists if allow_empty_list_or_dict otherwise skip empty dicts or lists. |
| 478 |
""" |
| 479 |
result = [] |
| 480 |
for item in alist: |
| 481 |
if isinstance(item, (list, dict)): |
| 482 |
sub = self.filter_out_none_entries(item, allow_empty_list_or_dict) |
| 483 |
if sub or allow_empty_list_or_dict: |
| 484 |
# allow empty dict or list if allow_empty_list_or_dict is set. |
| 485 |
# skip empty dict or list otherwise |
| 486 |
result.append(sub) |
| 487 |
elif item is not None: |
| 488 |
# skip None value |
| 489 |
result.append(item) |
| 490 |
return result |
| 491 |
|
| 492 |
def filter_out_none_entries(self, list_or_dict, allow_empty_list_or_dict=False): |
| 493 |
"""take a dict or list as input and return a dict/list without keys/elements whose values are None |
| 494 |
return empty dicts or lists if allow_empty_list_or_dict otherwise skip empty dicts or lists. |
| 495 |
""" |
| 496 |
|
| 497 |
if isinstance(list_or_dict, dict): |
| 498 |
return self._filter_out_none_entries_from_dict(list_or_dict, allow_empty_list_or_dict) |
| 499 |
|
| 500 |
if isinstance(list_or_dict, list): |
| 501 |
return self._filter_out_none_entries_from_list(list_or_dict, allow_empty_list_or_dict) |
| 502 |
|
| 503 |
raise TypeError('unexpected type %s' % type(list_or_dict)) |
| 504 |
|
| 505 |
@staticmethod |
| 506 |
def get_caller(depth): |
| 507 |
'''return the name of: |
| 508 |
our caller if depth is 1 |
| 509 |
the caller of our caller if depth is 2 |
| 510 |
the caller of the caller of our caller if depth is 3 |
| 511 |
... |
| 512 |
''' |
| 513 |
# one more caller in the stack |
| 514 |
depth += 1 |
| 515 |
frames = traceback.extract_stack(limit=depth) |
| 516 |
try: |
| 517 |
function_name = frames[0].name |
| 518 |
except AttributeError: |
| 519 |
# python 2.7 does not have named attributes for frames |
| 520 |
try: |
| 521 |
function_name = frames[0][2] |
| 522 |
except Exception as exc: # pylint: disable=broad-except |
| 523 |
function_name = 'Error retrieving function name: %s - %s' % (str(exc), repr(frames)) |
| 524 |
return function_name |
| 525 |
|
| 526 |
def fail_on_error(self, error, api=None, stack=False, depth=1, previous_errors=None): |
| 527 |
'''depth identifies how far is the caller in the call stack''' |
| 528 |
if error is None: |
| 529 |
return |
| 530 |
# one more caller to account for this function |
| 531 |
depth += 1 |
| 532 |
if api is not None: |
| 533 |
error = 'calling api: %s: %s' % (api, error) |
| 534 |
results = dict(msg='Error in %s: %s' % (self.get_caller(depth), error)) |
| 535 |
if stack: |
| 536 |
results['stack'] = traceback.format_stack() |
| 537 |
if previous_errors: |
| 538 |
results['previous_errors'] = ' - '.join(previous_errors) |
| 539 |
if getattr(self, 'ansible_module', None) is not None: |
| 540 |
self.ansible_module.fail_json(**results) |
| 541 |
raise AttributeError('Expecting self.ansible_module to be set when reporting %s' % repr(results)) |
| 542 |
|
| 543 |
def compare_chmod_value(self, current_permissions, desired_permissions): |
| 544 |
""" |
| 545 |
compare current unix_permissions to desired unix_permissions. |
| 546 |
:return: True if the same, False it not the same or desired unix_permissions is not valid. |
| 547 |
""" |
| 548 |
if current_permissions is None: |
| 549 |
return False |
| 550 |
if desired_permissions.isdigit(): |
| 551 |
return int(current_permissions) == int(desired_permissions) |
| 552 |
# ONTAP will throw error as invalid field if the length is not 9 or 12. |
| 553 |
if len(desired_permissions) not in [12, 9]: |
| 554 |
return False |
| 555 |
desired_octal_value = '' |
| 556 |
# if the length is 12, first three character sets userid('s'), groupid('s') and sticky('t') attributes |
| 557 |
if len(desired_permissions) == 12: |
| 558 |
if desired_permissions[0] not in ['s', '-'] or desired_permissions[1] not in ['s', '-']\ |
| 559 |
or desired_permissions[2] not in ['t', '-']: |
| 560 |
return False |
| 561 |
desired_octal_value += str(self.char_to_octal(desired_permissions[:3])) |
| 562 |
# if the len is 9, start from 0 else start from 3. |
| 563 |
start_range = len(desired_permissions) - 9 |
| 564 |
for i in range(start_range, len(desired_permissions), 3): |
| 565 |
if desired_permissions[i] not in ['r', '-'] or desired_permissions[i + 1] not in ['w', '-']\ |
| 566 |
or desired_permissions[i + 2] not in ['x', '-']: |
| 567 |
return False |
| 568 |
group_permission = self.char_to_octal(desired_permissions[i:i + 3]) |
| 569 |
desired_octal_value += str(group_permission) |
| 570 |
return int(current_permissions) == int(desired_octal_value) |
| 571 |
|
| 572 |
def char_to_octal(self, chars): |
| 573 |
""" |
| 574 |
:param chars: Characters to be converted into octal values. |
| 575 |
:return: octal value of the individual group permission. |
| 576 |
""" |
| 577 |
total = 0 |
| 578 |
if chars[0] in ['r', 's']: |
| 579 |
total += 4 |
| 580 |
if chars[1] in ['w', 's']: |
| 581 |
total += 2 |
| 582 |
if chars[2] in ['x', 't']: |
| 583 |
total += 1 |
| 584 |
return total |
| 585 |
|
| 586 |
def ignore_missing_vserver_on_delete(self, error, vserver_name=None): |
| 587 |
""" When a resource is expected to be absent, it's OK if the containing vserver is also absent. |
| 588 |
This function expects self.parameters('vserver') to be set or the vserver_name argument to be passed. |
| 589 |
error is an error returned by rest_generic.get_xxxx. |
| 590 |
""" |
| 591 |
if self.parameters.get('state') != 'absent': |
| 592 |
return False |
| 593 |
if vserver_name is None: |
| 594 |
if self.parameters.get('vserver') is None: |
| 595 |
self.ansible_module.fail_json( |
| 596 |
msg='Internal error, vserver name is required, when processing error: %s' % error, exception=traceback.format_exc()) |
| 597 |
vserver_name = self.parameters['vserver'] |
| 598 |
if isinstance(error, str): |
| 599 |
pass |
| 600 |
elif isinstance(error, dict): |
| 601 |
if 'message' in error: |
| 602 |
error = error['message'] |
| 603 |
else: |
| 604 |
self.ansible_module.fail_json( |
| 605 |
msg='Internal error, error should contain "message" key, found: %s' % error, exception=traceback.format_exc()) |
| 606 |
else: |
| 607 |
self.ansible_module.fail_json( |
| 608 |
msg='Internal error, error should be str or dict, found: %s, %s' % (type(error), error), exception=traceback.format_exc()) |
| 609 |
return 'SVM "%s" does not exist.' % vserver_name in error |
| 610 |
|
| 611 |
def remove_hal_links(self, records): |
| 612 |
""" Remove all _links entries """ |
| 613 |
if isinstance(records, dict): |
| 614 |
records.pop('_links', None) |
| 615 |
for record in records.values(): |
| 616 |
self.remove_hal_links(record) |
| 617 |
if isinstance(records, list): |
| 618 |
for record in records: |
| 619 |
self.remove_hal_links(record) |