Ejemplo n.º 1
0
def check_type_accesses(accesses: 'Any') -> dict:
    '''
    >>> check_type_accesses(dict())
    {}
    >>> check_type_accesses('{"/me": ["GET", "post"]}')
    {'/me': ['GET', 'POST']}
    >>> check_type_accesses({
    ...     '/me': [],
    ... })
    Traceback (most recent call last):
        ...
    ValueError: no permissions specfied for /me
    >>> check_type_accesses('GET')
    Traceback (most recent call last):
        ...
    TypeError: dictionary requested, could not parse JSON or key=value
    '''
    accesses = check_type_dict(accesses)
    result = accesses

    for (endpoint, perms) in accesses.items():
        endpoint = check_type_access_endpoint(endpoint)

        result[endpoint] = []

        methods = check_type_list(perms)
        if not methods:
            raise ValueError("no permissions specfied for %s" % endpoint)

        for method in methods:
            method = check_type_access_method(method)

            result[endpoint].append(method)

    return result
Ejemplo n.º 2
0
def _list_no_log_values(argument_spec, params):
    """Return set of no log values

    :arg argument_spec: An argument spec dictionary
    :arg params: Dictionary of all parameters

    :returns: Set of strings that should be hidden from output::

        {'secret_dict_value', 'secret_list_item_one', 'secret_list_item_two', 'secret_string'}
    """

    no_log_values = set()
    for arg_name, arg_opts in argument_spec.items():
        if arg_opts.get('no_log', False):
            # Find the value for the no_log'd param
            no_log_object = params.get(arg_name, None)

            if no_log_object:
                try:
                    no_log_values.update(
                        _return_datastructure_name(no_log_object))
                except TypeError as e:
                    raise TypeError('Failed to convert "%s": %s' %
                                    (arg_name, to_native(e)))

        # Get no_log values from suboptions
        sub_argument_spec = arg_opts.get('options')
        if sub_argument_spec is not None:
            wanted_type = arg_opts.get('type')
            sub_parameters = params.get(arg_name)

            if sub_parameters is not None:
                if wanted_type == 'dict' or (wanted_type == 'list'
                                             and arg_opts.get('elements',
                                                              '') == 'dict'):
                    # Sub parameters can be a dict or list of dicts. Ensure parameters are always a list.
                    if not isinstance(sub_parameters, list):
                        sub_parameters = [sub_parameters]

                    for sub_param in sub_parameters:
                        # Validate dict fields in case they came in as strings

                        if isinstance(sub_param, string_types):
                            sub_param = check_type_dict(sub_param)

                        if not isinstance(sub_param, Mapping):
                            raise TypeError(
                                "Value '{1}' in the sub parameter field '{0}' must by a {2}, "
                                "not '{1.__class__.__name__}'".format(
                                    arg_name, sub_param, wanted_type))

                        no_log_values.update(
                            _list_no_log_values(sub_argument_spec, sub_param))

    return no_log_values
Ejemplo n.º 3
0
    def check_if_nios_next_ip_exists(self, proposed_object):
        ''' Check if nios_next_ip argument is passed in ipaddr while creating
            host record, if yes then format proposed object ipv4addrs and pass
            func:nextavailableip and ipaddr range to create hostrecord with next
             available ip in one call to avoid any race condition '''

        if 'ipv4addrs' in proposed_object:
            if 'nios_next_ip' in proposed_object['ipv4addrs'][0]['ipv4addr']:
                ip_range = check_type_dict(proposed_object['ipv4addrs'][0]
                                           ['ipv4addr'])['nios_next_ip']
                proposed_object['ipv4addrs'][0][
                    'ipv4addr'] = NIOS_NEXT_AVAILABLE_IP + ':' + ip_range
        elif 'ipv4addr' in proposed_object:
            if 'nios_next_ip' in proposed_object['ipv4addr']:
                ip_range = check_type_dict(
                    proposed_object['ipv4addr'])['nios_next_ip']
                proposed_object[
                    'ipv4addr'] = NIOS_NEXT_AVAILABLE_IP + ':' + ip_range

        return proposed_object
Ejemplo n.º 4
0
def ensure_type(value, type_name):
    if type_name == 'str':
        return check_type_str(value)
    if type_name == 'list':
        return check_type_list(value)
    if type_name == 'dict':
        return check_type_dict(value)
    if type_name == 'bool':
        return check_type_bool(value)
    if type_name == 'int':
        return check_type_int(value)
    if type_name == 'float':
        return check_type_float(value)
    return value
    def _process_option_retries(self):
        '''check if retries option is int or dict and interpret it appropriately'''
        # this method focuses on validating the option, and setting a valid Retry object construction dict
        # it intentionally does not build the Session object, which will be done elsewhere

        retries_opt = self._options.get_option('retries')

        if retries_opt is None:
            return

        # we'll start with a copy of our defaults
        retries = self._RETRIES_DEFAULT_PARAMS.copy()

        try:
            # try int
            # on int, retry the specified number of times, and use the defaults for everything else
            # on zero, disable retries
            retries_int = check_type_int(retries_opt)

            if retries_int < 0:
                raise ValueError("Number of retries must be >= 0 (got %i)" %
                                 retries_int)
            elif retries_int == 0:
                retries = None
            else:
                retries['total'] = retries_int

        except TypeError:
            try:
                # try dict
                # on dict, use the value directly (will be used as the kwargs to initialize the Retry instance)
                retries = check_type_dict(retries_opt)
            except TypeError:
                raise TypeError(
                    "retries option must be interpretable as int or dict. Got: %r"
                    % retries_opt)

        self._options.set_option('retries', retries)
    def _process_option_proxies(self):
        '''check if 'proxies' option is dict or str and set it appropriately'''

        proxies_opt = self._options.get_option('proxies')

        if proxies_opt is None:
            return

        try:
            # if it can be interpreted as dict
            # do it
            proxies = check_type_dict(proxies_opt)
        except TypeError:
            # if it can't be interpreted as dict
            proxy = check_type_str(proxies_opt)
            # but can be interpreted as str
            # use this str as http and https proxy
            proxies = {
                'http': proxy,
                'https': proxy,
            }

        # record the new/interpreted value for 'proxies' option
        self._options.set_option('proxies', proxies)
Ejemplo n.º 7
0
 def _check_type_dict(self, value):
     return check_type_dict(value)
Ejemplo n.º 8
0
    def get_object_ref(self, module, ib_obj_type, obj_filter, ib_spec):
        ''' this function gets the reference object of pre-existing nios objects '''

        update = False
        old_name = new_name = None
        if ('name' in obj_filter):
            # gets and returns the current object based on name/old_name passed
            try:
                name_obj = check_type_dict(obj_filter['name'])
                old_name = name_obj['old_name']
                new_name = name_obj['new_name']
            except TypeError:
                name = obj_filter['name']

            if old_name and new_name:
                if (ib_obj_type == NIOS_HOST_RECORD):
                    test_obj_filter = dict([('name', old_name),
                                            ('view', obj_filter['view'])])
                elif (ib_obj_type in (NIOS_AAAA_RECORD, NIOS_A_RECORD)):
                    test_obj_filter = obj_filter
                else:
                    test_obj_filter = dict([('name', old_name)])
                # get the object reference
                ib_obj = self.get_object(ib_obj_type,
                                         test_obj_filter,
                                         return_fields=list(ib_spec.keys()))
                if ib_obj:
                    obj_filter['name'] = new_name
                else:
                    test_obj_filter['name'] = new_name
                    ib_obj = self.get_object(ib_obj_type,
                                             test_obj_filter,
                                             return_fields=list(
                                                 ib_spec.keys()))
                update = True
                return ib_obj, update, new_name
            if (ib_obj_type == NIOS_HOST_RECORD):
                # to check only by name if dns bypassing is set
                if not obj_filter['configure_for_dns']:
                    test_obj_filter = dict([('name', name)])
                else:
                    test_obj_filter = dict([('name', name),
                                            ('view', obj_filter['view'])])
            elif (ib_obj_type == NIOS_IPV4_FIXED_ADDRESS
                  or ib_obj_type == NIOS_IPV6_FIXED_ADDRESS
                  and 'mac' in obj_filter):
                test_obj_filter = dict([['mac', obj_filter['mac']]])
            elif (ib_obj_type == NIOS_A_RECORD):
                # resolves issue where a_record with uppercase name was returning null and was failing
                test_obj_filter = obj_filter
                test_obj_filter['name'] = test_obj_filter['name'].lower()
                # resolves issue where multiple a_records with same name and different IP address
                try:
                    ipaddr_obj = check_type_dict(obj_filter['ipv4addr'])
                    ipaddr = ipaddr_obj['old_ipv4addr']
                except TypeError:
                    ipaddr = obj_filter['ipv4addr']
                test_obj_filter['ipv4addr'] = ipaddr
            elif (ib_obj_type == NIOS_TXT_RECORD):
                # resolves issue where multiple txt_records with same name and different text
                test_obj_filter = obj_filter
                try:
                    text_obj = check_type_dict(obj_filter['text'])
                    txt = text_obj['old_text']
                except TypeError:
                    txt = obj_filter['text']
                test_obj_filter['text'] = txt
            # check if test_obj_filter is empty copy passed obj_filter
            else:
                test_obj_filter = obj_filter
            ib_obj = self.get_object(ib_obj_type,
                                     test_obj_filter.copy(),
                                     return_fields=list(ib_spec.keys()))
        elif (ib_obj_type == NIOS_A_RECORD):
            # resolves issue where multiple a_records with same name and different IP address
            test_obj_filter = obj_filter
            try:
                ipaddr_obj = check_type_dict(obj_filter['ipv4addr'])
                ipaddr = ipaddr_obj['old_ipv4addr']
            except TypeError:
                ipaddr = obj_filter['ipv4addr']
            test_obj_filter['ipv4addr'] = ipaddr
            ib_obj = self.get_object(ib_obj_type,
                                     test_obj_filter.copy(),
                                     return_fields=list(ib_spec.keys()))
        elif (ib_obj_type == NIOS_TXT_RECORD):
            # resolves issue where multiple txt_records with same name and different text
            test_obj_filter = obj_filter
            try:
                text_obj = check_type_dict(obj_filter['text'])
                txt = text_obj['old_text']
            except TypeError:
                txt = obj_filter['text']
            test_obj_filter['text'] = txt
            ib_obj = self.get_object(ib_obj_type,
                                     test_obj_filter.copy(),
                                     return_fields=list(ib_spec.keys()))
        elif (ib_obj_type == NIOS_ZONE):
            # del key 'restart_if_needed' as nios_zone get_object fails with the key present
            temp = ib_spec['restart_if_needed']
            del ib_spec['restart_if_needed']
            ib_obj = self.get_object(ib_obj_type,
                                     obj_filter.copy(),
                                     return_fields=list(ib_spec.keys()))
            # reinstate restart_if_needed if ib_obj is none, meaning there's no existing nios_zone ref
            if not ib_obj:
                ib_spec['restart_if_needed'] = temp
        elif (ib_obj_type == NIOS_MEMBER):
            # del key 'create_token' as nios_member get_object fails with the key present
            temp = ib_spec['create_token']
            del ib_spec['create_token']
            ib_obj = self.get_object(ib_obj_type,
                                     obj_filter.copy(),
                                     return_fields=list(ib_spec.keys()))
            if temp:
                # reinstate 'create_token' key
                ib_spec['create_token'] = temp
        else:
            ib_obj = self.get_object(ib_obj_type,
                                     obj_filter.copy(),
                                     return_fields=list(ib_spec.keys()))
        return ib_obj, update, new_name