Example #1
0
def add_portgroup_filter_by_node(query, value):
    if strutils.is_int_like(value):
        return query.filter_by(node_id=value)
    else:
        query = query.join(models.Node,
                           models.Portgroup.node_id == models.Node.id)
        return query.filter(models.Node.uuid == value)
Example #2
0
 def _add_location_filter_by_board(self, query, value):
     if strutils.is_int_like(value):
         return query.filter_by(board_id=value)
     else:
         query = query.join(models.Board,
                            models.Location.board_id == models.Board.id)
         return query.filter(models.Board.uuid == value)
Example #3
0
def extract_int(name, value, allow_zero=True, allow_negative=False):
    if value is None:
        return None

    if not strutils.is_int_like(value):
        raise ValueError(_("Only integer is acceptable by "
                           "'%(name)s'.") % {'name': name})

    if value in ('0', 0):
        if allow_zero:
            return int(value)
        raise ValueError(_("Only non-zero integer is acceptable by "
                           "'%(name)s'.") % {'name': name})
    try:
        result = int(value)
    except (TypeError, ValueError):
        raise ValueError(_("Value '%(value)s' is invalid for '%(name)s' "
                           "which only accepts integer.") %
                         {'name': name, 'value': value})

    if allow_negative is False and result < 0:
        raise ValueError(_("Value '%(value)s' is invalid for '%(name)s' "
                           "which only accepts non-negative integer.") %
                         {'name': name, 'value': value})

    return result
Example #4
0
        def parse_params(str_params, default):
            request_params = {}
            prog = re.compile('^(?:(.*),)?(%s)=(.*)$'
                              % "|".join(default.keys()))

            while str_params != "":
                match = prog.search(str_params)

                if match is None:
                    raise exception.IncorrectLease(err_msg)

                self.log.info("Matches: %s", match.groups())
                k, v = match.group(2, 3)
                if k in request_params.keys():
                    raise exception.DuplicatedLeaseParameters(err_msg)
                else:
                    if strutils.is_int_like(v):
                        request_params[k] = int(v)
                    else:
                        request_params[k] = v

                str_params = match.group(1) if match.group(1) else ""

            request_params.update({k: v for k, v in default.items()
                                   if k not in request_params.keys() and
                                   v is not None})
            return request_params
Example #5
0
def add_port_filter_by_portgroup(query, value):
    if strutils.is_int_like(value):
        return query.filter_by(portgroup_id=value)
    else:
        query = query.join(models.Portgroup,
                           models.Port.portgroup_id == models.Portgroup.id)
        return query.filter(models.Portgroup.uuid == value)
Example #6
0
def add_node_filter_by_chassis(query, value):
    if strutils.is_int_like(value):
        return query.filter_by(chassis_id=value)
    else:
        query = query.join(models.Chassis,
                           models.Node.chassis_id == models.Chassis.id)
        return query.filter(models.Chassis.uuid == value)
def get_api_version(version_string):
    """Returns checked APIVersion object"""
    version_string = str(version_string)
    if strutils.is_int_like(version_string):
        version_string = "%s.0" % version_string

    api_version = APIVersion(version_string)
    check_major_version(api_version)
    return api_version
Example #8
0
 def parse_params(params):
     match = prog.search(params)
     if match:
         k, v = match.group(2, 3)
         if strutils.is_int_like(v):
             v = int(v)
         res_info[k] = v
         if match.group(1) is not None:
             parse_params(match.group(1))
Example #9
0
    def get(cls, context, service_id):
        """Find a service based on its id or uuid and return a Board object.

        :param service_id: the id *or* uuid of a service.
        :returns: a :class:`Board` object.
        """
        if strutils.is_int_like(service_id):
            return cls.get_by_id(context, service_id)
        elif uuidutils.is_uuid_like(service_id):
            return cls.get_by_uuid(context, service_id)
        else:
            raise exception.InvalidIdentity(identity=service_id)
Example #10
0
 def __enter__(fa_self):
     task = tasks.pop(0)
     if isinstance(task, Exception):
         raise task
     # NOTE(comstud): Not ideal to throw this into
     # a helper, however it's the cleanest way
     # to verify we're dealing with the correct task/node.
     if strutils.is_int_like(fa_self.node_id):
         self.assertEqual(fa_self.node_id, task.node.id)
     else:
         self.assertEqual(fa_self.node_id, task.node.uuid)
     return task
Example #11
0
    def get(cls, context, node_id):
        """Find a node based on its id or uuid and return a Node object.

        :param node_id: the id *or* uuid of a node.
        :returns: a :class:`Node` object.
        """
        if strutils.is_int_like(node_id):
            return cls.get_by_id(context, node_id)
        elif uuidutils.is_uuid_like(node_id):
            return cls.get_by_uuid(context, node_id)
        else:
            raise exception.InvalidIdentity(identity=node_id)
Example #12
0
    def get(cls, context, chassis_id):
        """Find a chassis based on its id or uuid and return a Chassis object.

        :param chassis_id: the id *or* uuid of a chassis.
        :returns: a :class:`Chassis` object.
        """
        if strutils.is_int_like(chassis_id):
            return cls.get_by_id(context, chassis_id)
        elif uuidutils.is_uuid_like(chassis_id):
            return cls.get_by_uuid(context, chassis_id)
        else:
            raise exception.InvalidIdentity(identity=chassis_id)
Example #13
0
    def get(cls, context, session_or_board_uuid):
        """Find a session based on its id or uuid and return a SessionWP object.

        :param session_id: the id *or* uuid of a session.
        :returns: a :class:`SessionWP` object.
        """
        if strutils.is_int_like(session_or_board_uuid):
            return cls.get_by_id(context, session_or_board_uuid)
        elif uuidutils.is_uuid_like(session_or_board_uuid):
            return cls.get_session_by_board_uuid(context,
                                                 session_or_board_uuid)
        else:
            raise exception.InvalidIdentity(identity=session_or_board_uuid)
Example #14
0
    def get(cls, context, federation_id):
        """Find a federation based on its id or uuid and return it.

        :param federation_id: the id *or* uuid of a federation.
        :param context: Security context
        :returns: a :class:`Federation` object.
        """
        if strutils.is_int_like(federation_id):
            return cls.get_by_id(context, federation_id)
        elif uuidutils.is_uuid_like(federation_id):
            return cls.get_by_uuid(context, federation_id)
        else:
            raise exception.InvalidIdentity(identity=federation_id)
Example #15
0
    def get(cls, context, baymodel_id):
        """Find a baymodel based on its id or uuid and return a BayModel object.

        :param baymodel_id: the id *or* uuid of a baymodel.
        :param context: Security context
        :returns: a :class:`BayModel` object.
        """
        if strutils.is_int_like(baymodel_id):
            return cls.get_by_id(context, baymodel_id)
        elif uuidutils.is_uuid_like(baymodel_id):
            return cls.get_by_uuid(context, baymodel_id)
        else:
            raise exception.InvalidIdentity(identity=baymodel_id)
Example #16
0
    def get(cls, context, cluster_id):
        """Find a cluster based on its id or uuid and return a Cluster object.

        :param cluster_id: the id *or* uuid of a cluster.
        :param context: Security context
        :returns: a :class:`Cluster` object.
        """
        if strutils.is_int_like(cluster_id):
            return cls.get_by_id(context, cluster_id)
        elif uuidutils.is_uuid_like(cluster_id):
            return cls.get_by_uuid(context, cluster_id)
        else:
            raise exception.InvalidIdentity(identity=cluster_id)
Example #17
0
    def get(cls, context, port_id):
        """Find a port based on its id or uuid and return a Port object.

        :param port_id: the id *or* uuid of a port.
        :returns: a :class:`Port` object.
        """
        if strutils.is_int_like(port_id):
            return cls.get_by_id(context, port_id)
        elif uuidutils.is_uuid_like(port_id):
            return cls.get_by_uuid(context, port_id)
        elif utils.is_valid_mac(port_id):
            return cls.get_by_address(context, port_id)
        else:
            raise exception.InvalidIdentity(identity=port_id)
def get_api_version(version_string):
    """Returns checked APIVersion object"""
    version_string = str(version_string)
    if version_string in DEPRECATED_VERSIONS:
        LOG.warning("Version %(deprecated_version)s is deprecated, use "
                    "alternative version %(alternative)s instead.",
                   {"deprecated_version": version_string,
                    "alternative": DEPRECATED_VERSIONS[version_string]})
    if strutils.is_int_like(version_string):
        version_string = "%s.0" % version_string

    api_version = APIVersion(version_string)
    check_major_version(api_version)
    return api_version
Example #19
0
    def get(cls, context, x509keypair_id):
        """Find a X509KeyPair based on its id or uuid.

        Find X509KeyPair by id or uuid and return a X509KeyPair object.

        :param x509keypair_id: the id *or* uuid of a x509keypair.
        :param context: Security context
        :returns: a :class:`X509KeyPair` object.
        """
        if strutils.is_int_like(x509keypair_id):
            return cls.get_by_id(context, x509keypair_id)
        elif uuidutils.is_uuid_like(x509keypair_id):
            return cls.get_by_uuid(context, x509keypair_id)
        else:
            raise exception.InvalidIdentity(identity=x509keypair_id)
Example #20
0
def add_identity_filter(query, value):
    """Adds an identity filter to a query.

    Filters results by ID, if supplied value is a valid integer.
    Otherwise attempts to filter results by UUID.

    :param query: Initial query to add filter to.
    :param value: Value for filtering results by.
    :return: Modified query.
    """
    if strutils.is_int_like(value):
        return query.filter_by(id=value)
    elif uuidutils.is_uuid_like(value):
        return query.filter_by(uuid=value)
    else:
        raise exception.InvalidIdentity(identity=value)
Example #21
0
    def get(cls, context, allocation_ident):
        """Find an allocation by its ID, UUID or name.

        :param allocation_ident: The ID, UUID or name of an allocation.
        :param context: Security context
        :returns: An :class:`Allocation` object.
        :raises: InvalidIdentity

        """
        if strutils.is_int_like(allocation_ident):
            return cls.get_by_id(context, allocation_ident)
        elif uuidutils.is_uuid_like(allocation_ident):
            return cls.get_by_uuid(context, allocation_ident)
        elif utils.is_valid_logical_name(allocation_ident):
            return cls.get_by_name(context, allocation_ident)
        else:
            raise exception.InvalidIdentity(identity=allocation_ident)
Example #22
0
    def get(cls, context, allocation_ident):
        """Find an allocation by its ID, UUID or name.

        :param allocation_ident: The ID, UUID or name of an allocation.
        :param context: Security context
        :returns: An :class:`Allocation` object.
        :raises: InvalidIdentity

        """
        if strutils.is_int_like(allocation_ident):
            return cls.get_by_id(context, allocation_ident)
        elif uuidutils.is_uuid_like(allocation_ident):
            return cls.get_by_uuid(context, allocation_ident)
        elif utils.is_valid_logical_name(allocation_ident):
            return cls.get_by_name(context, allocation_ident)
        else:
            raise exception.InvalidIdentity(identity=allocation_ident)
Example #23
0
    def get(cls, context, ident):
        """Find a volume target based on its ID or UUID.

        :param context: security context
        :param ident: the database primary key ID *or* the UUID of a volume
                      target
        :returns: a :class:`VolumeTarget` object
        :raises: InvalidIdentity if ident is neither an integer ID nor a UUID
        :raises: VolumeTargetNotFound if no volume target with this ident
                 exists
        """
        if strutils.is_int_like(ident):
            return cls.get_by_id(context, ident)
        elif uuidutils.is_uuid_like(ident):
            return cls.get_by_uuid(context, ident)
        else:
            raise exception.InvalidIdentity(identity=ident)
Example #24
0
    def get(cls, context, ident):
        """Find a volume connector based on its ID or UUID.

        :param context: security context
        :param ident: the database primary key ID *or* the UUID of a volume
                      connector
        :returns: a :class:`VolumeConnector` object
        :raises: InvalidIdentity if ident is neither an integer ID nor a UUID
        :raises: VolumeConnectorNotFound if no volume connector exists with
                 the specified ident
        """
        if strutils.is_int_like(ident):
            return cls.get_by_id(context, ident)
        elif uuidutils.is_uuid_like(ident):
            return cls.get_by_uuid(context, ident)
        else:
            raise exception.InvalidIdentity(identity=ident)
Example #25
0
    def check_params(self, values):
        if 'network_id' not in values:
            raise manager_ex.MissingParameter(param='network_id')

        if 'amount' not in values:
            raise manager_ex.MissingParameter(param='amount')

        if not strutils.is_int_like(values['amount']):
            raise manager_ex.MalformedParameter(param='amount')

        # required_floatingips param is an optional parameter
        fips = values.get('required_floatingips', [])
        if not isinstance(fips, list):
            manager_ex.MalformedParameter(param='required_floatingips')

        for ip in fips:
            if not (netutils.is_valid_ipv4(ip) or netutils.is_valid_ipv6(ip)):
                raise manager_ex.InvalidIPFormat(ip=ip)
Example #26
0
    def get(cls, context, port_id):
        """Find a port.

        Find a port based on its id or uuid or MAC address and return a Port
        object.

        :param port_id: the id *or* uuid *or* MAC address of a port.
        :returns: a :class:`Port` object.
        :raises: InvalidIdentity

        """
        if strutils.is_int_like(port_id):
            return cls.get_by_id(context, port_id)
        elif uuidutils.is_uuid_like(port_id):
            return cls.get_by_uuid(context, port_id)
        elif utils.is_valid_mac(port_id):
            return cls.get_by_address(context, port_id)
        else:
            raise exception.InvalidIdentity(identity=port_id)
Example #27
0
    def get(cls, context, portgroup_ident):
        """Find a portgroup based on its id, uuid, name or address.

        :param portgroup_ident: The id, uuid, name or address of a portgroup.
        :param context: Security context
        :returns: A :class:`Portgroup` object.
        :raises: InvalidIdentity

        """
        if strutils.is_int_like(portgroup_ident):
            return cls.get_by_id(context, portgroup_ident)
        elif uuidutils.is_uuid_like(portgroup_ident):
            return cls.get_by_uuid(context, portgroup_ident)
        elif netutils.is_valid_mac(portgroup_ident):
            return cls.get_by_address(context, portgroup_ident)
        elif utils.is_valid_logical_name(portgroup_ident):
            return cls.get_by_name(context, portgroup_ident)
        else:
            raise exception.InvalidIdentity(identity=portgroup_ident)
Example #28
0
    def get(cls, context, portgroup_ident):
        """Find a portgroup based on its id, uuid, name or address.

        :param portgroup_ident: The id, uuid, name or address of a portgroup.
        :param context: Security context
        :returns: A :class:`Portgroup` object.
        :raises: InvalidIdentity

        """
        if strutils.is_int_like(portgroup_ident):
            return cls.get_by_id(context, portgroup_ident)
        elif uuidutils.is_uuid_like(portgroup_ident):
            return cls.get_by_uuid(context, portgroup_ident)
        elif utils.is_valid_mac(portgroup_ident):
            return cls.get_by_address(context, portgroup_ident)
        elif utils.is_valid_logical_name(portgroup_ident):
            return cls.get_by_name(context, portgroup_ident)
        else:
            raise exception.InvalidIdentity(identity=portgroup_ident)
Example #29
0
def add_filter_by_many_identities(query, model, values):
    """Adds an identity filter to a query for values list.

    Filters results by ID, if supplied values contain a valid integer.
    Otherwise attempts to filter results by UUID.

    :param query: Initial query to add filter to.
    :param model: Model for filter.
    :param values: Values for filtering results by.
    :return: tuple (Modified query, filter field name).
    """
    if not values:
        raise exception.InvalidIdentity(identity=values)
    value = values[0]
    if strutils.is_int_like(value):
        return query.filter(getattr(model, 'id').in_(values)), 'id'
    elif uuidutils.is_uuid_like(value):
        return query.filter(getattr(model, 'uuid').in_(values)), 'uuid'
    else:
        raise exception.InvalidIdentity(identity=value)
Example #30
0
    def __init__(self, options):
        """Initialize a new Infoblox object instance

        Args:
            options (dict): Target options dictionary
        """

        config = cfg.CONF['backend:infoblox']

        reqd_opts = ['wapi_url', 'username', 'password', 'ns_group']
        other_opts = ['sslverify', 'network_view', 'dns_view', 'multi_tenant']

        for opt in reqd_opts + other_opts:
            if opt == 'sslverify' or opt == 'multi_tenant':
                # NOTE(selvakumar): This check is for sslverify option.
                # type of sslverify is unicode string from designate DB
                # if the value is 0 getattr called for setting default values.
                # to avoid setting default values we use oslo strutils
                if not strutils.is_int_like(options.get(opt)):
                    option_value = options.get(opt)
                else:
                    option_value = strutils.bool_from_string(options.get(opt),
                                                             default=True)
                setattr(self, opt, option_value)
                continue
            setattr(self, opt, options.get(opt) or getattr(config, opt))

        for opt in reqd_opts:
            LOG.debug("self.%s = %s", opt, getattr(self, opt))
            if not getattr(self, opt):
                raise exc.InfobloxIsMisconfigured(option=opt)

        self.session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(
            pool_connections=config.http_pool_connections,
            pool_maxsize=config.http_pool_maxsize)
        self.session.mount('http://', adapter)
        self.session.mount('https://', adapter)
        self.session.auth = (self.username, self.password)
        self.session.verify = self.sslverify
Example #31
0
    def __init__(self, options):
        """Initialize a new Infoblox object instance

        Args:
            options (dict): Target options dictionary
        """

        config = cfg.CONF['backend:infoblox']

        reqd_opts = ['wapi_url', 'username', 'password', 'ns_group']
        other_opts = ['sslverify', 'network_view', 'dns_view', 'multi_tenant']

        for opt in reqd_opts + other_opts:
            if opt == 'sslverify' or opt == 'multi_tenant':
                # NOTE(selvakumar): This check is for sslverify option.
                # type of sslverify is unicode string from designate DB
                # if the value is 0 getattr called for setting default values.
                # to avoid setting default values we use oslo strutils
                if not strutils.is_int_like(options.get(opt)):
                    option_value = options.get(opt)
                else:
                    option_value = strutils.bool_from_string(options.get(opt),
                                                             default=True)
                setattr(self, opt, option_value)
                continue
            setattr(self, opt, options.get(opt) or getattr(config, opt))

        for opt in reqd_opts:
            LOG.debug("self.%s = %s", opt, getattr(self, opt))
            if not getattr(self, opt):
                raise exc.InfobloxIsMisconfigured(option=opt)

        self.session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(
            pool_connections=config.http_pool_connections,
            pool_maxsize=config.http_pool_maxsize)
        self.session.mount('http://', adapter)
        self.session.mount('https://', adapter)
        self.session.auth = (self.username, self.password)
        self.session.verify = self.sslverify
Example #32
0
def validate_integer(value, name, min_value=None, max_value=None):
    """Make sure that value is a valid integer, potentially within range.

    :param value: the value of the integer
    :param name: the name of the integer
    :param min_length: the min_length of the integer
    :param max_length: the max_length of the integer
    :returns: integer
    """
    if not strutils.is_int_like(value):
        raise webob.exc.HTTPBadRequest(explanation=(
            _('%s must be an integer.') % name))
    value = int(value)

    if min_value is not None and value < min_value:
        raise webob.exc.HTTPBadRequest(
            explanation=(_('%(value_name)s must be >= %(min_value)d') %
                         {'value_name': name, 'min_value': min_value}))
    if max_value is not None and value > max_value:
        raise webob.exc.HTTPBadRequest(
            explanation=(_('%(value_name)s must be <= %(max_value)d') %
                         {'value_name': name, 'max_value': max_value}))

    return value
Example #33
0
def validate_integer(value, name, min_value=None, max_value=None):
    """Make sure that value is a valid integer, potentially within range.

    :param value: the value of the integer
    :param name: the name of the integer
    :param min_length: the min_length of the integer
    :param max_length: the max_length of the integer
    :returns: integer
    """
    if not strutils.is_int_like(value):
        raise webob.exc.HTTPBadRequest(explanation=(
            _('%s must be an integer.') % name))
    value = int(value)

    if min_value is not None and value < min_value:
        raise webob.exc.HTTPBadRequest(
            explanation=(_('%(value_name)s must be >= %(min_value)d') %
                         {'value_name': name, 'min_value': min_value}))
    if max_value is not None and value > max_value:
        raise webob.exc.HTTPBadRequest(
            explanation=(_('%(value_name)s must be <= %(max_value)d') %
                         {'value_name': name, 'max_value': max_value}))

    return value
Example #34
0
    def args2body(self, parsed_args):
        def parse_params(str_params, default):
            request_params = {}
            prog = re.compile('^(?:(.*),)?(%s)=(.*)$'
                              % "|".join(default.keys()))

            while str_params != "":
                match = prog.search(str_params)

                if match is None:
                    raise exception.IncorrectLease(err_msg)

                self.log.info("Matches: %s", match.groups())
                k, v = match.group(2, 3)
                if k in request_params.keys():
                    raise exception.DuplicatedLeaseParameters(err_msg)
                else:
                    if strutils.is_int_like(v):
                        request_params[k] = int(v)
                    else:
                        request_params[k] = v

                str_params = match.group(1) if match.group(1) else ""

            request_params.update({k: v for k, v in default.items()
                                   if k not in request_params.keys() and
                                   v is not None})
            return request_params

        params = {}
        if parsed_args.name:
            params['name'] = parsed_args.name
        if not isinstance(parsed_args.start, datetime.datetime):
            if parsed_args.start != 'now':
                try:
                    parsed_args.start = datetime.datetime.strptime(
                        parsed_args.start, '%Y-%m-%d %H:%M')
                except ValueError:
                    raise exception.IncorrectLease
        if not isinstance(parsed_args.end, datetime.datetime):
            try:
                parsed_args.end = datetime.datetime.strptime(
                    parsed_args.end, '%Y-%m-%d %H:%M')
            except ValueError:
                raise exception.IncorrectLease

        if parsed_args.start == 'now':
            start = datetime.datetime.utcnow()
        else:
            start = parsed_args.start

        if start > parsed_args.end:
            raise exception.IncorrectLease

        if parsed_args.before_end:
            try:
                parsed_args.before_end = datetime.datetime.strptime(
                    parsed_args.before_end, '%Y-%m-%d %H:%M')
            except ValueError:
                raise exception.IncorrectLease
            if (parsed_args.before_end < start or
                    parsed_args.end < parsed_args.before_end):
                raise exception.IncorrectLease
            params['before_end'] = datetime.datetime.strftime(
                parsed_args.before_end, '%Y-%m-%d %H:%M')

        if parsed_args.start == 'now':
            params['start'] = parsed_args.start
        else:
            params['start'] = datetime.datetime.strftime(parsed_args.start,
                                                         '%Y-%m-%d %H:%M')
        params['end'] = datetime.datetime.strftime(parsed_args.end,
                                                   '%Y-%m-%d %H:%M')

        params['reservations'] = []
        params['events'] = []

        physical_reservations = []
        for phys_res_str in parsed_args.physical_reservations:
            err_msg = ("Invalid physical-reservation argument '%s'. "
                       "Reservation arguments must be of the "
                       "form --physical-reservation <min=int,max=int,"
                       "hypervisor_properties=str,resource_properties=str,"
                       "before_end=str>"
                       % phys_res_str)
            defaults = CREATE_RESERVATION_KEYS["physical:host"]
            phys_res_info = parse_params(phys_res_str, defaults)

            if not (phys_res_info['min'] and phys_res_info['max']):
                raise exception.IncorrectLease(err_msg)

            if not (strutils.is_int_like(phys_res_info['min']) and
                    strutils.is_int_like(phys_res_info['max'])):
                raise exception.IncorrectLease(err_msg)

            min_host = int(phys_res_info['min'])
            max_host = int(phys_res_info['max'])

            if min_host > max_host:
                err_msg = ("Invalid physical-reservation argument '%s'. "
                           "Reservation argument min value must be "
                           "less than max value"
                           % phys_res_str)
                raise exception.IncorrectLease(err_msg)

            if min_host == 0 or max_host == 0:
                err_msg = ("Invalid physical-reservation argument '%s'. "
                           "Reservation arguments min and max values "
                           "must be greater than or equal to 1"
                           % phys_res_str)
                raise exception.IncorrectLease(err_msg)

            # NOTE(sbauza): The resource type should be conf-driven mapped with
            #               blazar.conf file but that's potentially on another
            #               host
            phys_res_info['resource_type'] = 'physical:host'
            physical_reservations.append(phys_res_info)
        if physical_reservations:
            params['reservations'] += physical_reservations

        reservations = []
        for res_str in parsed_args.reservations:
            err_msg = ("Invalid reservation argument '%s'. "
                       "Reservation arguments must be of the "
                       "form --reservation <key=value>"
                       % res_str)

            if "physical:host" in res_str:
                defaults = CREATE_RESERVATION_KEYS['physical:host']
            elif "virtual:instance" in res_str:
                defaults = CREATE_RESERVATION_KEYS['virtual:instance']
            else:
                defaults = CREATE_RESERVATION_KEYS['others']

            res_info = parse_params(res_str, defaults)
            reservations.append(res_info)

        if reservations:
            params['reservations'] += reservations

        if not params['reservations']:
            raise exception.IncorrectLease

        events = []
        for event_str in parsed_args.events:
            err_msg = ("Invalid event argument '%s'. "
                       "Event arguments must be of the "
                       "form --event <event_type=str,event_date=time>"
                       % event_str)
            event_info = {"event_type": "", "event_date": ""}
            for kv_str in event_str.split(","):
                try:
                    k, v = kv_str.split("=", 1)
                except ValueError:
                    raise exception.IncorrectLease(err_msg)
                if k in event_info:
                    event_info[k] = v
                else:
                    raise exception.IncorrectLease(err_msg)
            if not event_info['event_type'] and not event_info['event_date']:
                raise exception.IncorrectLease(err_msg)
            event_date = event_info['event_date']
            try:
                date = datetime.datetime.strptime(event_date, '%Y-%m-%d %H:%M')
                event_date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M')
                event_info['event_date'] = event_date
            except ValueError:
                raise exception.IncorrectLease
            events.append(event_info)
        if events:
            params['events'] = events

        return params
Example #35
0
def add_port_filter_by_node(query, value):
    if strutils.is_int_like(value):
        return query.filter_by(node_id=value)
    else:
        query = query.join(models.Node, models.Port.node_id == models.Node.id)
        return query.filter(models.Node.uuid == value)
Example #36
0
 def test_is_int_like_false(self):
     self.assertFalse(strutils.is_int_like(1.1))
     self.assertFalse(strutils.is_int_like("1.1"))
     self.assertFalse(strutils.is_int_like("1.1.1"))
     self.assertFalse(strutils.is_int_like(None))
     self.assertFalse(strutils.is_int_like("0."))
     self.assertFalse(strutils.is_int_like("aaaaaa"))
     self.assertFalse(strutils.is_int_like("...."))
     self.assertFalse(strutils.is_int_like("1g"))
     self.assertFalse(
         strutils.is_int_like("0cc3346e-9fef-4445-abe6-5d2b2690ec64"))
     self.assertFalse(strutils.is_int_like("a1"))
     # NOTE(viktors): 12e3 - is a float number
     self.assertFalse(strutils.is_int_like("12e3"))
     # NOTE(viktors): Check integer numbers with base not 10
     self.assertFalse(strutils.is_int_like("0o51"))
     self.assertFalse(strutils.is_int_like("0xDEADBEEF"))
Example #37
0
 def test_is_int_like_true(self):
     self.assertTrue(strutils.is_int_like(1))
     self.assertTrue(strutils.is_int_like("1"))
     self.assertTrue(strutils.is_int_like("514"))
     self.assertTrue(strutils.is_int_like("0"))
Example #38
0
def add_subcloud_resource_filter_by_subcloud(query, value):
    if strutils.is_int_like(value):
        return query.filter(models.Subcloud.id == value)
    elif uuidutils.is_uuid_like(value):
        return query.filter(models.Subcloud.uuid == value)
Example #39
0
def _validate_key_size(param_value):
    if param_value is not None:
        if not strutils.is_int_like(param_value):
            raise exception.InvalidInput(
                reason=(_('key_size must be an integer.')))
    return True
Example #40
0
File: api.py Project: cotyb/nova
 def get_floating_ip(self, context, id):
     if not strutils.is_int_like(id):
         raise exception.InvalidID(id=id)
     return objects.FloatingIP.get_by_id(context, id)
Example #41
0
    def args2body(self, parsed_args):
        def parse_params(str_params, default):
            request_params = {}
            prog = re.compile('^(?:(.*),)?(%s)=(.*)$' %
                              "|".join(default.keys()))

            while str_params != "":
                match = prog.search(str_params)

                if match is None:
                    raise exception.IncorrectLease(err_msg)

                self.log.info("Matches: %s", match.groups())
                k, v = match.group(2, 3)
                if k in request_params.keys():
                    raise exception.DuplicatedLeaseParameters(err_msg)
                else:
                    if strutils.is_int_like(v):
                        request_params[k] = int(v)
                    elif isinstance(defaults[k], list):
                        request_params[k] = jsonutils.loads(v)
                    else:
                        request_params[k] = v

                str_params = match.group(1) if match.group(1) else ""

            request_params.update({
                k: v
                for k, v in default.items()
                if k not in request_params.keys() and v is not None
            })
            return request_params

        params = {}
        if parsed_args.name:
            params['name'] = parsed_args.name
        if not isinstance(parsed_args.start, datetime.datetime):
            if parsed_args.start != 'now':
                try:
                    parsed_args.start = datetime.datetime.strptime(
                        parsed_args.start, '%Y-%m-%d %H:%M')
                except ValueError:
                    raise exception.IncorrectLease
        if not isinstance(parsed_args.end, datetime.datetime):
            try:
                parsed_args.end = datetime.datetime.strptime(
                    parsed_args.end, '%Y-%m-%d %H:%M')
            except ValueError:
                raise exception.IncorrectLease

        if parsed_args.start == 'now':
            start = _utc_now()
        else:
            start = parsed_args.start

        if start > parsed_args.end:
            raise exception.IncorrectLease

        if parsed_args.before_end:
            try:
                parsed_args.before_end = datetime.datetime.strptime(
                    parsed_args.before_end, '%Y-%m-%d %H:%M')
            except ValueError:
                raise exception.IncorrectLease
            if (parsed_args.before_end < start
                    or parsed_args.end < parsed_args.before_end):
                raise exception.IncorrectLease
            params['before_end'] = datetime.datetime.strftime(
                parsed_args.before_end, '%Y-%m-%d %H:%M')

        if parsed_args.start == 'now':
            params['start'] = parsed_args.start
        else:
            params['start'] = datetime.datetime.strftime(
                parsed_args.start, '%Y-%m-%d %H:%M')
        params['end'] = datetime.datetime.strftime(parsed_args.end,
                                                   '%Y-%m-%d %H:%M')

        params['reservations'] = []
        params['events'] = []

        physical_reservations = []
        for phys_res_str in parsed_args.physical_reservations:
            err_msg = ("Invalid physical-reservation argument '%s'. "
                       "Reservation arguments must be of the "
                       "form --physical-reservation <min=int,max=int,"
                       "hypervisor_properties=str,resource_properties=str,"
                       "before_end=str>" % phys_res_str)
            defaults = CREATE_RESERVATION_KEYS["physical:host"]
            phys_res_info = parse_params(phys_res_str, defaults)

            if not (phys_res_info['min'] and phys_res_info['max']):
                raise exception.IncorrectLease(err_msg)

            if not (strutils.is_int_like(phys_res_info['min'])
                    and strutils.is_int_like(phys_res_info['max'])):
                raise exception.IncorrectLease(err_msg)

            min_host = int(phys_res_info['min'])
            max_host = int(phys_res_info['max'])

            if min_host > max_host:
                err_msg = ("Invalid physical-reservation argument '%s'. "
                           "Reservation argument min value must be "
                           "less than max value" % phys_res_str)
                raise exception.IncorrectLease(err_msg)

            if min_host == 0 or max_host == 0:
                err_msg = ("Invalid physical-reservation argument '%s'. "
                           "Reservation arguments min and max values "
                           "must be greater than or equal to 1" % phys_res_str)
                raise exception.IncorrectLease(err_msg)

            # NOTE(sbauza): The resource type should be conf-driven mapped with
            #               blazar.conf file but that's potentially on another
            #               host
            phys_res_info['resource_type'] = 'physical:host'
            physical_reservations.append(phys_res_info)
        if physical_reservations:
            params['reservations'] += physical_reservations

        reservations = []
        for res_str in parsed_args.reservations:
            err_msg = ("Invalid reservation argument '%s'. "
                       "Reservation arguments must be of the "
                       "form --reservation <key=value>" % res_str)

            if "physical:host" in res_str:
                defaults = CREATE_RESERVATION_KEYS['physical:host']
            elif "virtual:instance" in res_str:
                defaults = CREATE_RESERVATION_KEYS['virtual:instance']
            elif "virtual:floatingip" in res_str:
                defaults = CREATE_RESERVATION_KEYS['virtual:floatingip']
            else:
                defaults = CREATE_RESERVATION_KEYS['others']

            res_info = parse_params(res_str, defaults)
            reservations.append(res_info)

        if reservations:
            params['reservations'] += reservations

        if not params['reservations']:
            raise exception.IncorrectLease

        events = []
        for event_str in parsed_args.events:
            err_msg = ("Invalid event argument '%s'. "
                       "Event arguments must be of the "
                       "form --event <event_type=str,event_date=time>" %
                       event_str)
            event_info = {"event_type": "", "event_date": ""}
            for kv_str in event_str.split(","):
                try:
                    k, v = kv_str.split("=", 1)
                except ValueError:
                    raise exception.IncorrectLease(err_msg)
                if k in event_info:
                    event_info[k] = v
                else:
                    raise exception.IncorrectLease(err_msg)
            if not event_info['event_type'] and not event_info['event_date']:
                raise exception.IncorrectLease(err_msg)
            event_date = event_info['event_date']
            try:
                date = datetime.datetime.strptime(event_date, '%Y-%m-%d %H:%M')
                event_date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M')
                event_info['event_date'] = event_date
            except ValueError:
                raise exception.IncorrectLease
            events.append(event_info)
        if events:
            params['events'] = events

        return params
Example #42
0
 def get_floating_ip(self, context, id):
     if not strutils.is_int_like(id):
         raise exception.InvalidID(id=id)
     return objects.FloatingIP.get_by_id(context, id)
Example #43
0
    def args2body(self, parsed_args):
        params = {}
        if parsed_args.name:
            params['name'] = parsed_args.name
        if not isinstance(parsed_args.start, datetime.datetime):
            try:
                parsed_args.start = datetime.datetime.strptime(
                    parsed_args.start, '%Y-%m-%d %H:%M')
            except ValueError:
                raise exception.IncorrectLease
        if not isinstance(parsed_args.end, datetime.datetime):
            try:
                parsed_args.end = datetime.datetime.strptime(
                    parsed_args.end, '%Y-%m-%d %H:%M')
            except ValueError:
                raise exception.IncorrectLease
        if parsed_args.start > parsed_args.end:
            raise exception.IncorrectLease

        if parsed_args.before_end:
            try:
                parsed_args.before_end = datetime.datetime.strptime(
                    parsed_args.before_end, '%Y-%m-%d %H:%M')
            except ValueError:
                raise exception.IncorrectLease
            if (parsed_args.before_end < parsed_args.start
                    or parsed_args.end < parsed_args.before_end):
                raise exception.IncorrectLease
            params['before_end'] = datetime.datetime.strftime(
                parsed_args.before_end, '%Y-%m-%d %H:%M')

        params['start'] = datetime.datetime.strftime(parsed_args.start,
                                                     '%Y-%m-%d %H:%M')
        params['end'] = datetime.datetime.strftime(parsed_args.end,
                                                   '%Y-%m-%d %H:%M')

        params['reservations'] = []
        params['events'] = []

        physical_reservations = []
        for phys_res_str in parsed_args.physical_reservations:
            err_msg = ("Invalid physical-reservation argument '%s'. "
                       "Reservation arguments must be of the "
                       "form --physical-reservation <min=int,max=int,"
                       "hypervisor_properties=str,resource_properties=str,"
                       "before_end=str>"
                       % phys_res_str)
            phys_res_info = {"min": "", "max": "", "hypervisor_properties": "",
                             "resource_properties": "", "before_end": None}
            prog = re.compile('^(?:(.*),)?(%s)=(.*)$'
                              % "|".join(phys_res_info.keys()))

            def parse_params(params):
                match = prog.search(params)
                if match:
                    self.log.info("Matches: %s", match.groups())
                    k, v = match.group(2, 3)
                    if not phys_res_info[k]:
                        phys_res_info[k] = v
                    else:
                        raise exception.DuplicatedLeaseParameters(err_msg)
                    if match.group(1) is not None:
                        parse_params(match.group(1))
                else:
                    raise exception.IncorrectLease(err_msg)

            parse_params(phys_res_str)
            if not (phys_res_info['min'] and phys_res_info['max']):
                raise exception.IncorrectLease(err_msg)

            if not (strutils.is_int_like(phys_res_info['min']) and
                    strutils.is_int_like(phys_res_info['max'])):
                raise exception.IncorrectLease(err_msg)

            min_host = int(phys_res_info['min'])
            max_host = int(phys_res_info['max'])

            if min_host > max_host:
                err_msg = ("Invalid physical-reservation argument '%s'. "
                           "Reservation argument min value must be "
                           "less than max value"
                           % phys_res_str)
                raise exception.IncorrectLease(err_msg)

            if min_host == 0 or max_host == 0:
                err_msg = ("Invalid physical-reservation argument '%s'. "
                           "Reservation arguments min and max values "
                           "must be greater than or equal to 1"
                           % phys_res_str)
                raise exception.IncorrectLease(err_msg)

            if phys_res_info['before_end'] is None:
                phys_res_info.pop('before_end')
            # NOTE(sbauza): The resource type should be conf-driven mapped with
            #               blazar.conf file but that's potentially on another
            #               host
            phys_res_info['resource_type'] = 'physical:host'
            physical_reservations.append(phys_res_info)
        if physical_reservations:
            params['reservations'] += physical_reservations

        reservations = []
        for res_str in parsed_args.reservations:
            err_msg = ("Invalid reservation argument '%s'. "
                       "Reservation arguments must be of the "
                       "form --reservation <key=value>"
                       % res_str)
            res_info = {}
            for kv_str in res_str.split(","):
                try:
                    k, v = kv_str.split("=", 1)
                except ValueError:
                    raise exception.IncorrectLease(err_msg)
                if strutils.is_int_like(v):
                    v = int(v)
                res_info[k] = v
            reservations.append(res_info)
        if reservations:
            params['reservations'] += reservations

        if not params['reservations']:
            raise exception.IncorrectLease

        events = []
        for event_str in parsed_args.events:
            err_msg = ("Invalid event argument '%s'. "
                       "Event arguments must be of the "
                       "form --event <event_type=str,event_date=time>"
                       % event_str)
            event_info = {"event_type": "", "event_date": ""}
            for kv_str in event_str.split(","):
                try:
                    k, v = kv_str.split("=", 1)
                except ValueError:
                    raise exception.IncorrectLease(err_msg)
                if k in event_info:
                    event_info[k] = v
                else:
                    raise exception.IncorrectLease(err_msg)
            if not event_info['event_type'] and not event_info['event_date']:
                raise exception.IncorrectLease(err_msg)
            event_date = event_info['event_date']
            try:
                date = datetime.datetime.strptime(event_date, '%Y-%m-%d %H:%M')
                event_date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M')
                event_info['event_date'] = event_date
            except ValueError:
                raise exception.IncorrectLease
            events.append(event_info)
        if events:
            params['events'] = events

        return params
Example #44
0
def add_orch_request_filter_by_resource(query, value):
    if strutils.is_int_like(value):
        return query.filter(models.OrchRequest.id == value)
    elif uuidutils.is_uuid_like(value):
        return query.filter(models.OrchRequest.uuid == value)
Example #45
0
 def test_is_int_like_true(self):
     self.assertTrue(strutils.is_int_like(1))
     self.assertTrue(strutils.is_int_like("1"))
     self.assertTrue(strutils.is_int_like("514"))
     self.assertTrue(strutils.is_int_like("0"))
Example #46
0
def _validate_key_size(param_value):
    if param_value is not None:
        if not strutils.is_int_like(param_value):
            raise exception.InvalidInput(reason=(
                _('key_size must be an integer.')))
    return True
Example #47
0
    def _validate_data_type(self, target):
        if not self.values:
            msg = ("Rule '%(rule)s' contains empty value")
            raise exception.ValidationError(msg % {"rule": self})

        special_attribute = self._attribute_special_field(target)
        if special_attribute:
            attribute_info = target.get(special_attribute)
        else:
            attribute_info = target.get(self.attribute)

        for value in self.values:
            error = False
            if attribute_info[1] == 'string' and not isinstance(
                    value, six.string_types):
                error = True
            elif attribute_info[1] == 'number':
                if not strutils.is_int_like(value):
                    error = True
            elif attribute_info[1] == 'uuid':
                if not uuidutils.is_uuid_like(value):
                    error = True
            elif attribute_info[1] == 'datetime':
                try:
                    timeutils.parse_isotime(value)
                except ValueError:
                    error = True
            elif attribute_info[1] == 'enum':
                if value not in attribute_info[3]:
                    msg = ("Rule '%(rule)s' contains data type '%(type)s' "
                           "with invalid value. It should be one of "
                           "%(valid_value)s")
                    raise exception.ValidationError(
                        msg % {
                            "rule": self,
                            "valid_value": ",".join(attribute_info[3]),
                            'type': attribute_info[1]
                        })

            if error:
                msg = ("Rule '%(rule)s' contains invalid data type for value "
                       "'%(value)s'. The data type should be '%(type)s'")
                raise exception.ValidationError(msg % {
                    "rule": self,
                    "value": value,
                    'type': attribute_info[1]
                })

            # Also, check whether the data type is supported by operator
            if attribute_info[1] not in \
                    self.OPERATOR_SUPPORTED_DATA_TYPES.get(self.operator):
                msg = ("Rule '%(rule)s' contains operator '%(operator)s' "
                       "which doesn't support data type '%(type)s' for "
                       "attribute '%(attribute)s'")
                raise exception.ValidationError(
                    msg % {
                        "rule": self,
                        "operator": self.operator,
                        'type': attribute_info[1],
                        'attribute': self.attribute
                    })
Example #48
0
 def test_is_int_like_false(self):
     self.assertFalse(strutils.is_int_like(1.1))
     self.assertFalse(strutils.is_int_like("1.1"))
     self.assertFalse(strutils.is_int_like("1.1.1"))
     self.assertFalse(strutils.is_int_like(None))
     self.assertFalse(strutils.is_int_like("0."))
     self.assertFalse(strutils.is_int_like("aaaaaa"))
     self.assertFalse(strutils.is_int_like("...."))
     self.assertFalse(strutils.is_int_like("1g"))
     self.assertFalse(strutils.is_int_like("0cc3346e-9fef-4445-abe6-5d2b2690ec64"))
     self.assertFalse(strutils.is_int_like("a1"))
     # NOTE(viktors): 12e3 - is a float number
     self.assertFalse(strutils.is_int_like("12e3"))
     # NOTE(viktors): Check integer numbers with base not 10
     self.assertFalse(strutils.is_int_like("0o51"))
     self.assertFalse(strutils.is_int_like("0xDEADBEEF"))