Python neutron_lib.exceptions.InvalidInput() Examples

The following are 30 code examples of neutron_lib.exceptions.InvalidInput(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module neutron_lib.exceptions , or try the search function .
Example #1
Source File: ovs_ext_lib.py    From networking-sfc with Apache License 2.0 6 votes vote down vote up
def get_port_mask(min_port, max_port):
    """get port/mask serial by port range."""
    if min_port < 1 or max_port > 0xffff or min_port > max_port:
        msg = _("the port range is invalid")
        raise exceptions.InvalidInput(error_message=msg)
    masks = []
    while min_port <= max_port:
        mask = 0xffff
        while mask != 0:
            next_mask = (mask << 1) & 0xffff
            port_start = min_port & next_mask
            port_end = min_port + (next_mask ^ 0xffff)
            if port_start == min_port and port_end <= max_port:
                mask = next_mask
            else:
                break
        masks.append('0x%x/0x%x' % (min_port, mask))
        min_port = min_port + (mask ^ 0xffff) + 1

    return masks 
Example #2
Source File: converters.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def convert_kvp_list_to_dict(kvp_list):
    """Convert a list of 'key=value' strings to a dict.

    :param kvp_list: A list of key value pair strings. For more info on the
        format see; convert_kvp_str_to_list().
    :returns: A dict who's key value pairs are populated by parsing 'kvp_list'.
    :raises InvalidInput: If any of the key value strings are malformed.
    """
    if kvp_list == ['True']:
        # No values were provided (i.e. '--flag-name')
        return {}
    kvp_map = {}
    for kvp_str in kvp_list:
        key, value = convert_kvp_str_to_list(kvp_str)
        kvp_map.setdefault(key, set())
        kvp_map[key].add(value)
    return dict((x, list(y)) for x, y in kvp_map.items()) 
Example #3
Source File: converters.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def convert_to_positive_float_or_none(val):
    """Converts a value to a python float if the value is positive.

    :param val: The value to convert to a positive python float.
    :returns: The value as a python float. If the val is None, None is
        returned.
    :raises ValueError, InvalidInput: A ValueError is raised if the 'val'
        is a float, but is negative. InvalidInput is raised if 'val' can't be
        converted to a python float.
    """
    # NOTE(salv-orlando): This conversion function is currently used by
    # a vendor specific extension only at the moment  It is used for
    # port's RXTX factor in neutron.plugins.vmware.extensions.qos.
    # It is deemed however generic enough to be in this module as it
    # might be used in future for other API attributes.
    if val is None:
        return
    try:
        val = float(val)
        if val < 0:
            raise ValueError()
    except (ValueError, TypeError):
        msg = _("'%s' must be a non negative decimal") % val
        raise n_exc.InvalidInput(error_message=msg)
    return val 
Example #4
Source File: __init__.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def validate_any_key_specs_or_none(data, key_specs=None):
    """Validate each dict in a list matches at least 1 key_spec.

    :param data: The list of dicts to validate.
    :param key_specs: An iterable collection of key spec dicts that is used
        to check each dict in data.
    :returns: None.
    :raises InvalidInput: If any of the dicts in data do not match at least
        1 of the key_specs given.
    """
    if data is None:
        return

    def dict_validator(data_dict):
        msg = _validate_any_key_spec(data_dict, key_specs=key_specs)
        if msg:
            raise n_exc.InvalidInput(error_message=msg)

    msg = _validate_list_of_items(dict_validator, data)
    if msg:
        raise n_exc.InvalidInput(error_message=msg) 
Example #5
Source File: test_validators.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def test_validate_no_whitespace(self):
        data = 'no_white_space'
        result = validators.validate_no_whitespace(data)
        self.assertEqual(data, result)

        self.assertRaises(n_exc.InvalidInput,
                          validators.validate_no_whitespace,
                          'i have whitespace')

        self.assertRaises(n_exc.InvalidInput,
                          validators.validate_no_whitespace,
                          'i\thave\twhitespace')

        for ws in string.whitespace:
            self.assertRaises(n_exc.InvalidInput,
                              validators.validate_no_whitespace,
                              '%swhitespace-at-head' % ws)
            self.assertRaises(n_exc.InvalidInput,
                              validators.validate_no_whitespace,
                              'whitespace-at-tail%s' % ws) 
Example #6
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_assert_error_on_non_string(self):
        for invalid in [[], 123]:
            with testtools.ExpectedException(n_exc.InvalidInput):
                converters.convert_string_to_case_insensitive(invalid) 
Example #7
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_unknown_string(self):
        with testtools.ExpectedException(n_exc.InvalidInput):
            converters.convert_to_protocol("Invalid") 
Example #8
Source File: converters.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def convert_string_to_case_insensitive(data):
    """Convert a string value into a lower case string.

    This effectively makes the string case-insensitive.

    :param data: The value to convert.
    :return: The lower-cased string representation of the value, or None is
        'data' is None.
    :raises InvalidInput: If the value is not a string.
    """
    try:
        return data.lower()
    except AttributeError:
        error_message = _("Input value %s must be string type") % data
        raise n_exc.InvalidInput(error_message=error_message) 
Example #9
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_numeric_too_low(self):
        with testtools.ExpectedException(n_exc.InvalidInput):
            converters.convert_to_protocol("-1") 
Example #10
Source File: converters.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def convert_to_protocol(data):
    """Validate that a specified IP protocol is valid.

    For the authoritative list mapping protocol names to numbers, see the IANA:
    http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml

    :param data: The value to verify is an IP protocol.
    :returns: If data is an int between 0 and 255 or None, return that; if
        data is a string then return it lower-cased if it matches one of the
        allowed protocol names.
    :raises exceptions.InvalidInput: If data is an int < 0, an
        int > 255, or a string that does not match one of the allowed protocol
        names.
    """

    if data is None:
        return
    val = convert_string_to_case_insensitive(data)
    if val in constants.IPTABLES_PROTOCOL_MAP:
        return data

    error_message = _("IP protocol '%s' is not supported. Only protocol "
                      "names and their integer representation (0 to "
                      "255) are supported") % data
    try:
        if validators.validate_range(convert_to_int(data), [0, 255]) is None:
            return data
        else:
            raise n_exc.InvalidInput(error_message=error_message)
    except n_exc.InvalidInput:
        raise n_exc.InvalidInput(error_message=error_message) 
Example #11
Source File: __init__.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def validate_no_whitespace(data):
    """Validates that input has no whitespace.

    :param data: The data to validate. Must be a python string type suitable
        for searching via regex.
    :returns: The data itself.
    :raises InvalidInput: If the data contains whitespace.
    """
    if re.search(r'\s', data):
        msg = _("'%s' contains whitespace") % data
        LOG.debug(msg)
        raise n_exc.InvalidInput(error_message=msg)
    return data 
Example #12
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_numeric_too_high(self):
        with testtools.ExpectedException(n_exc.InvalidInput):
            converters.convert_to_protocol("300") 
Example #13
Source File: availability_zone.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def _validate_availability_zone_hints(data, valid_value=None):
    msg = validators.validate_list_of_unique_strings(data)
    if msg:
        return msg
    az_string = convert_az_list_to_string(data)
    if len(az_string) > db_const.AZ_HINTS_DB_LEN:
        msg = _("Too many availability_zone_hints specified")
        raise exceptions.InvalidInput(error_message=msg) 
Example #14
Source File: attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def convert_values(
            self, res_dict,
            exc_cls=lambda m: exceptions.InvalidInput(error_message=m)):
        """Convert and validate attribute values for a request.

        :param res_dict: The resource attributes from the request.
        :param exc_cls: Exception to be raised on error that must take
            a single error message as it's only constructor arg.
        :raises: exc_cls If any errors occur converting/validating the
            res_dict.
        """
        for attr, attr_vals in self.attributes.items():
            if (attr not in res_dict or
                    res_dict[attr] is constants.ATTR_NOT_SPECIFIED):
                continue
            # Convert values if necessary
            if 'convert_to' in attr_vals:
                res_dict[attr] = attr_vals['convert_to'](res_dict[attr])
            # Check that configured values are correct
            if 'validate' not in attr_vals:
                continue
            for rule in attr_vals['validate']:
                validator = validators.get_validator(rule)
                res = validator(res_dict[attr],
                                attr_vals['validate'][rule])
                if res:
                    msg_dict = dict(attr=attr, reason=res)
                    msg = _("Invalid input for %(attr)s. "
                            "Reason: %(reason)s.") % msg_dict
                    raise exc_cls(msg) 
Example #15
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_fill_no_default_value_allow_post(self):
        attr_info = {
            'key': {
                'allow_post': True,
            },
        }
        attr_inst = attributes.AttributeInfo(attr_info)
        self._test_fill_default_value(attr_inst, {'key': 'X'}, {'key': 'X'})
        self.assertRaises(exceptions.InvalidInput,
                          self._test_fill_default_value,
                          attr_inst, {'key': 'X'}, {})
        self.assertRaises(self._EXC_CLS, attr_inst.fill_post_defaults,
                          {}, self._EXC_CLS) 
Example #16
Source File: test_attributes.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_fill_no_default_value_no_allow_post(self):
        attr_info = {
            'key': {
                'allow_post': False,
            },
        }
        attr_inst = attributes.AttributeInfo(attr_info)
        self.assertRaises(exceptions.InvalidInput,
                          self._test_fill_default_value,
                          attr_inst, {'key': 'X'}, {'key': 'X'})
        self._test_fill_default_value(attr_inst, {}, {})
        self.assertRaises(self._EXC_CLS, attr_inst.fill_post_defaults,
                          {'key': 'X'}, self._EXC_CLS) 
Example #17
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_convert_non_ip_addr_with_slash(self):
        with testtools.ExpectedException(n_exc.InvalidInput):
            converters.convert_cidr_to_canonical_format(
                u"Dormamu/DarkSeid/Vulture") 
Example #18
Source File: test_validators.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_data_is_not_list(self):
        for t in [dict(), set(), 'abc', 1, True]:
            self.assertRaises(
                n_exc.InvalidInput,
                validators.validate_any_key_specs_or_none, t, key_specs={}) 
Example #19
Source File: test_validators.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_data_invalid_keys(self):
        data = [{'opt_name': 'a', 'opt_value': 'A'},
                {'opt_name': 'b', 'opt_valuee': 'B'}]
        self.assertRaisesRegex(
            n_exc.InvalidInput,
            "No valid key specs",
            validators.validate_any_key_specs_or_none,
            data, key_specs=extra_dhcp_opt.EXTRA_DHCP_OPT_KEY_SPECS) 
Example #20
Source File: test_validators.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_data_optional_key_invalid(self):
        data = [{'opt_name': 'a', 'opt_value': 'A'},
                {'opt_name': 'b', 'opt_value': 'B', 'ip_version': '3'}]
        self.assertRaisesRegex(
            n_exc.InvalidInput,
            "No valid key specs",
            validators.validate_any_key_specs_or_none,
            data, key_specs=extra_dhcp_opt.EXTRA_DHCP_OPT_KEY_SPECS) 
Example #21
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_convert_to_boolean_int(self):
        self.assertIs(converters.convert_to_boolean(0), False)
        self.assertIs(converters.convert_to_boolean(1), True)
        self.assertRaises(n_exc.InvalidInput,
                          converters.convert_to_boolean,
                          7) 
Example #22
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_convert_to_int_str(self):
        self.assertEqual(4, converters.convert_to_int('4'))
        self.assertEqual(6, converters.convert_to_int('6'))
        self.assertRaises(n_exc.InvalidInput,
                          converters.convert_to_int,
                          'garbage') 
Example #23
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_convert_to_int_none(self):
        self.assertRaises(n_exc.InvalidInput,
                          converters.convert_to_int,
                          None) 
Example #24
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_convert_to_float_negative_value(self):
        self.assertRaises(n_exc.InvalidInput,
                          converters.convert_to_positive_float_or_none,
                          -1.11) 
Example #25
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_convert_to_float_string(self):
        self.assertEqual(4, converters.convert_to_positive_float_or_none('4'))
        self.assertEqual(
            4.44, converters.convert_to_positive_float_or_none('4.44'))
        self.assertRaises(n_exc.InvalidInput,
                          converters.convert_to_positive_float_or_none,
                          'garbage') 
Example #26
Source File: test_conversions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_convert_kvp_str_to_list_fails_for_missing_key(self):
        with testtools.ExpectedException(n_exc.InvalidInput):
            converters.convert_kvp_str_to_list('=a') 
Example #27
Source File: l2gw_midonet_validators.py    From networking-midonet with Apache License 2.0 5 votes vote down vote up
def validate_network_mapping_list_without_seg_id_validation(network_mapping,
                                                            check_vlan):
    """Validate network mapping list in connection."""
    if network_mapping.get('segmentation_id'):
        if check_vlan:
            raise exceptions.InvalidInput(
                error_message=_("default segmentation_id should not be"
                                " provided when segmentation_id is assigned"
                                " during l2gateway creation"))
        # This method doen't check segmentation id range.

    if not network_mapping.get('segmentation_id'):
        if check_vlan is False:
            raise exceptions.InvalidInput(
                error_message=_("Segmentation id must be specified in create "
                                "l2gateway connections"))
    network_id = network_mapping.get(l2gw_const.NETWORK_ID)
    if not network_id:
        raise exceptions.InvalidInput(
            error_message=_("A valid network identifier must be specified "
                            "when connecting a network to a network "
                            "gateway. Unable to complete operation"))
    connection_attrs = set(network_mapping.keys())
    if not connection_attrs.issubset(l2gw_validators.
                                     ALLOWED_CONNECTION_ATTRIBUTES):
        raise exceptions.InvalidInput(
            error_message=(_("Invalid keys found among the ones provided "
                             "in request : %(connection_attrs)s."),
                           connection_attrs))
    return network_id 
Example #28
Source File: ovs_ext_lib.py    From networking-sfc with Apache License 2.0 5 votes vote down vote up
def do_action_groups(self, action, kwargs_list):
        group_strs = [_build_group_expr_str(kw, action) for kw in kwargs_list]
        if action == 'add' or action == 'del':
            cmd = '%s-groups' % action
        elif action == 'mod':
            cmd = '%s-group' % action
        else:
            msg = _("Action is illegal")
            raise exceptions.InvalidInput(error_message=msg)
        self.run_ofctl(cmd, ['-'], '\n'.join(group_strs)) 
Example #29
Source File: ovs_ext_lib.py    From networking-sfc with Apache License 2.0 5 votes vote down vote up
def _build_group_expr_str(group_dict, cmd):
    group_expr_arr = []
    buckets = None
    group_id = None

    if cmd != 'del':
        if "group_id" not in group_dict:
            msg = _("Must specify one group Id on group addition"
                    " or modification")
            raise exceptions.InvalidInput(error_message=msg)
        group_id = "group_id=%s" % group_dict.pop('group_id')

        if "buckets" not in group_dict:
            msg = _("Must specify one or more buckets on group addition"
                    " or modification")
            raise exceptions.InvalidInput(error_message=msg)
        buckets = "%s" % group_dict.pop('buckets')

    if group_id:
        group_expr_arr.append(group_id)

    for key, value in group_dict.items():
        group_expr_arr.append("%s=%s" % (key, value))

    if buckets:
        group_expr_arr.append(buckets)

    return ','.join(group_expr_arr) 
Example #30
Source File: test_ovs_ext_lib.py    From networking-sfc with Apache License 2.0 5 votes vote down vote up
def test_invalid_min_port(self):
        self.assertRaises(
            exceptions.InvalidInput,
            ovs_ext_lib.get_port_mask,
            0, 100
        )