コード例 #1
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: value of the integer
    :param name: name of the integer
    :param min_value: min_value of the integer
    :param max_value: max_value of the integer
    :returns: integer
    :raises: ValueError if value is an invalid integer

    .. versionadded:: 3.33
    """
    try:
        value = int(str(value))
    except (ValueError, UnicodeEncodeError):
        msg = _('%(value_name)s must be an integer') % {'value_name': name}
        raise ValueError(msg)

    if min_value is not None and value < min_value:
        msg = _('%(value_name)s must be >= %(min_value)d') % {
            'value_name': name,
            'min_value': min_value
        }
        raise ValueError(msg)

    if max_value is not None and value > max_value:
        msg = _('%(value_name)s must be <= %(max_value)d') % {
            'value_name': name,
            'max_value': max_value
        }
        raise ValueError(msg)

    return value
コード例 #2
0
def check_string_length(value, name=None, min_length=0, max_length=None):
    """Check the length of specified string.

    :param value: the value of the string
    :param name: the name of the string
    :param min_length: the min_length of the string
    :param max_length: the max_length of the string
    :raises TypeError, ValueError: For any invalid input.

    .. versionadded:: 3.7
    """
    if name is None:
        name = value

    if not isinstance(value, six.string_types):
        msg = _("%s is not a string or unicode") % name
        raise TypeError(msg)

    length = len(value)
    if length < min_length:
        msg = _("%(name)s has %(length)s characters, less than "
                "%(min_length)s.") % {'name': name, 'length': length,
                                      'min_length': min_length}
        raise ValueError(msg)

    if max_length and length > max_length:
        msg = _("%(name)s has %(length)s characters, more than "
                "%(max_length)s.") % {'name': name, 'length': length,
                                      'max_length': max_length}
        raise ValueError(msg)
コード例 #3
0
ファイル: strutils.py プロジェクト: Rahul529/appoint
def check_string_length(value, name=None, min_length=0, max_length=None):
    """Check the length of specified string.

    :param value: the value of the string
    :param name: the name of the string
    :param min_length: the min_length of the string
    :param max_length: the max_length of the string
    :raises TypeError, ValueError: For any invalid input.

    .. versionadded:: 3.7
    """
    if name is None:
        name = value

    if not isinstance(value, six.string_types):
        msg = _("%s is not a string or unicode") % name
        raise TypeError(msg)

    length = len(value)
    if length < min_length:
        msg = _("%(name)s has %(length)s characters, less than "
                "%(min_length)s.") % {'name': name, 'length': length,
                                      'min_length': min_length}
        raise ValueError(msg)

    if max_length and length > max_length:
        msg = _("%(name)s has %(length)s characters, more than "
                "%(max_length)s.") % {'name': name, 'length': length,
                                      'max_length': max_length}
        raise ValueError(msg)
コード例 #4
0
ファイル: strutils.py プロジェクト: openstack/oslo.utils
def validate_integer(value, name, min_value=None, max_value=None):
    """Make sure that value is a valid integer, potentially within range.

    :param value: value of the integer
    :param name: name of the integer
    :param min_value: min_value of the integer
    :param max_value: max_value of the integer
    :returns: integer
    :raises: ValueError if value is an invalid integer

    .. versionadded:: 3.33
    """
    try:
        value = int(str(value))
    except (ValueError, UnicodeEncodeError):
        msg = _('%(value_name)s must be an integer'
                ) % {'value_name': name}
        raise ValueError(msg)

    if min_value is not None and value < min_value:
        msg = _('%(value_name)s must be >= %(min_value)d'
                ) % {'value_name': name, 'min_value': min_value}
        raise ValueError(msg)

    if max_value is not None and value > max_value:
        msg = _('%(value_name)s must be <= %(max_value)d'
                ) % {'value_name': name, 'max_value': max_value}
        raise ValueError(msg)

    return value
コード例 #5
0
ファイル: netutils.py プロジェクト: bdrich/neutron-lbaas
def get_ipv6_addr_by_EUI64(prefix, mac):
    """Calculate IPv6 address using EUI-64 specification.

    This method calculates the IPv6 address using the EUI-64
    addressing scheme as explained in rfc2373.

    :param prefix: IPv6 prefix.
    :param mac: IEEE 802 48-bit MAC address.
    :returns: IPv6 address on success.
    :raises ValueError, TypeError: For any invalid input.

    .. versionadded:: 1.4
    """
    # Check if the prefix is an IPv4 address
    if netaddr.valid_ipv4(prefix):
        msg = _("Unable to generate IP address by EUI64 for IPv4 prefix")
        raise ValueError(msg)
    try:
        eui64 = int(netaddr.EUI(mac).eui64())
        prefix = netaddr.IPNetwork(prefix)
        return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
    except (ValueError, netaddr.AddrFormatError):
        raise ValueError(_('Bad prefix or mac format for generating IPv6 '
                           'address by EUI-64: %(prefix)s, %(mac)s:')
                         % {'prefix': prefix, 'mac': mac})
    except TypeError:
        raise TypeError(_('Bad prefix type for generating IPv6 address by '
                          'EUI-64: %s') % prefix)
コード例 #6
0
def get_ipv6_addr_by_EUI64(prefix, mac):
    """Calculate IPv6 address using EUI-64 specification.

    This method calculates the IPv6 address using the EUI-64
    addressing scheme as explained in rfc2373.

    :param prefix: IPv6 prefix.
    :param mac: IEEE 802 48-bit MAC address.
    :returns: IPv6 address on success.
    :raises ValueError, TypeError: For any invalid input.

    .. versionadded:: 1.4
    """
    # Check if the prefix is an IPv4 address
    if is_valid_ipv4(prefix):
        msg = _("Unable to generate IP address by EUI64 for IPv4 prefix")
        raise ValueError(msg)
    try:
        eui64 = int(netaddr.EUI(mac).eui64())
        prefix = netaddr.IPNetwork(prefix)
        return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
    except (ValueError, netaddr.AddrFormatError):
        raise ValueError(
            _('Bad prefix or mac format for generating IPv6 '
              'address by EUI-64: %(prefix)s, %(mac)s:') % {
                  'prefix': prefix,
                  'mac': mac
              })
    except TypeError:
        raise TypeError(
            _('Bad prefix type for generating IPv6 address by '
              'EUI-64: %s') % prefix)
コード例 #7
0
 def validate(patch):
     result = (super(ClusterPatchType, ClusterPatchType).validate(patch))
     if patch.op in ['add', 'remove']:
         msg = _("Attributes cannot be added or removed")
         raise wsme.exc.ClientSideError(msg % patch.path)
     if patch.path in patch.readonly_attrs():
         msg = _("'%s' is a read-only attribute and can not be updated")
         raise wsme.exc.ClientSideError(msg % patch.path)
     return result
コード例 #8
0
 def _validate_network(cls, network, prefix):
     """
     Validates that the prefix is valid for the IP address family.
     """
     try:
         value = netaddr.IPNetwork(network + "/" + str(prefix))
     except netaddr.core.AddrFormatError:
         raise ValueError(_("Invalid IP address and prefix"))
     mask = value.hostmask
     host = value.ip & mask
     if host.value != 0:
         raise ValueError(_("Host bits must be zero"))
コード例 #9
0
ファイル: strutils.py プロジェクト: hpcjmart/Openstack
def split_path(path, minsegs=1, maxsegs=None, rest_with_last=False):
    """Validate and split the given HTTP request path.

    **Examples**::

        ['a'] = _split_path('/a')
        ['a', None] = _split_path('/a', 1, 2)
        ['a', 'c'] = _split_path('/a/c', 1, 2)
        ['a', 'c', 'o/r'] = _split_path('/a/c/o/r', 1, 3, True)

    :param path: HTTP Request path to be split
    :param minsegs: Minimum number of segments to be extracted
    :param maxsegs: Maximum number of segments to be extracted
    :param rest_with_last: If True, trailing data will be returned as part
                           of last segment.  If False, and there is
                           trailing data, raises ValueError.
    :returns: list of segments with a length of maxsegs (non-existent
              segments will return as None)
    :raises: ValueError if given an invalid path

    .. versionadded:: 3.11
    """
    if not maxsegs:
        maxsegs = minsegs
    if minsegs > maxsegs:
        raise ValueError(
            _('minsegs > maxsegs: %(min)d > %(max)d)') % {
                'min': minsegs,
                'max': maxsegs
            })
    if rest_with_last:
        segs = path.split('/', maxsegs)
        minsegs += 1
        maxsegs += 1
        count = len(segs)
        if (segs[0] or count < minsegs or count > maxsegs
                or '' in segs[1:minsegs]):
            raise ValueError(_('Invalid path: %s') % urllib.parse.quote(path))
    else:
        minsegs += 1
        maxsegs += 1
        segs = path.split('/', maxsegs)
        count = len(segs)
        if (segs[0] or count < minsegs or count > maxsegs + 1
                or '' in segs[1:minsegs]
                or (count == maxsegs + 1 and segs[maxsegs])):
            raise ValueError(_('Invalid path: %s') % urllib.parse.quote(path))
    segs = segs[1:maxsegs]
    segs.extend([None] * (maxsegs - 1 - len(segs)))
    return segs
コード例 #10
0
ファイル: alarm.py プロジェクト: starlingx/fault
    def post(self, alarm_data):
        """Create an alarm/event log.
        :param alarm_data: All information required to create an
         alarm or eventlog.
        """

        alarm_data_dict = alarm_data.as_dict()
        alarm_state = alarm_data_dict['alarm_state']
        try:
            if alarm_state == fm_constants.FM_ALARM_STATE_SET:
                data = pecan.request.dbapi.alarm_create(alarm_data_dict)
                tmp_dict = data.as_dict()
                self._alarm_save2event_log(tmp_dict, alarm_state)
            elif (alarm_state == fm_constants.FM_ALARM_STATE_LOG
                  or alarm_state == fm_constants.FM_ALARM_STATE_MSG):
                data = self._alarm_save2event_log(alarm_data_dict, 'log')
            # This is same action as DELETE Method if para is uuid
            # keep this RESTful for future use to clear/delete alarm with parameters
            # are alarm_id and entity_instance_id
            elif alarm_state == fm_constants.FM_ALARM_STATE_CLEAR:
                clear_uuid = alarm_data_dict['uuid']
                alarm_id = alarm_data_dict['alarm_id']
                entity_instance_id = alarm_data_dict['entity_instance_id']
                if clear_uuid is not None:
                    data = pecan.request.dbapi.alarm_get(clear_uuid)
                    pecan.request.dbapi.alarm_destroy(clear_uuid)
                    tmp_dict = data.as_dict()
                    self._alarm_save2event_log(tmp_dict,
                                               alarm_state,
                                               empty_uuid=True)
                elif alarm_id is not None and entity_instance_id is not None:
                    data = pecan.request.dbapi.alarm_get_by_ids(
                        alarm_id, entity_instance_id)
                    if data is None:
                        raise wsme.exc.ClientSideError(
                            _("can not find record to clear!"))
                    pecan.request.dbapi.alarm_destroy_by_ids(
                        alarm_id, entity_instance_id)
                    tmp_dict = data.as_dict()
                    self._alarm_save2event_log(tmp_dict,
                                               alarm_state,
                                               empty_uuid=True)
            else:
                msg = _("The alarm_state %s does not support!")
                raise wsme.exc.ClientSideError(msg % alarm_state)
        except Exception as err:
            return err
        alarm_dict = data.as_dict()
        return json.dumps({"uuid": alarm_dict['uuid']})
コード例 #11
0
def do_load_import(cc, args):
    """Import a load."""
    # If absolute path is not specified, we assume it is the relative path.
    # args.isopath will then be set to the absolute path
    if not os.path.isabs(args.isopath):
        args.isopath = os.path.abspath(args.isopath)

    if not os.path.isabs(args.sigpath):
        args.sigpath = os.path.abspath(args.sigpath)

    if not os.path.isfile(args.isopath):
        raise exc.CommandError(_("File %s does not exist." % args.isopath))

    if not os.path.isfile(args.sigpath):
        raise exc.CommandError(_("File %s does not exist." % args.sigpath))

    active = None
    if args.active is True:
        active = 'true'
    else:
        # The following logic is taken from sysinv api as it takes a while for
        # this large POST request to reach the server.
        #
        # Ensure the request does not exceed load import limit before sending.

        loads = cc.load.list()
        if len(loads) > IMPORTED_LOAD_MAX_COUNT:
            raise exc.CommandError(
                _("Max number of loads (2) reached. Please remove the "
                  "old or unused load before importing a new one."))

    patch = {
        'path_to_iso': args.isopath,
        'path_to_sig': args.sigpath,
        'active': active
    }

    try:
        print("This operation will take a while. Please wait.")
        wait_task = WaitThread()
        wait_task.start()
        imported_load = cc.load.import_load(**patch)
        wait_task.join()
    except Exception as e:
        wait_task.join()
        raise exc.CommandError(_("Load import failed. Reason: %s" % e))
    else:
        _print_load_show(imported_load)
コード例 #12
0
ファイル: base.py プロジェクト: starlingx/fault
    def parse_headers(headers, default_version, latest_version):
        """Determine the API version requested based on the headers supplied.

        :param headers: webob headers
        :param default_version: version to use if not specified in headers
        :param latest_version: version to use if latest is requested
        :returns: a tupe of (major, minor) version numbers
        :raises: webob.HTTPNotAcceptable
        """
        version_str = headers.get(Version.string, default_version)

        if version_str.lower() == 'latest':
            parse_str = latest_version
        else:
            parse_str = version_str

        try:
            version = tuple(int(i) for i in parse_str.split('.'))
        except ValueError:
            version = ()

        if len(version) != 2:
            raise exc.HTTPNotAcceptable(
                _("Invalid value for %s header") % Version.string)
        return version
コード例 #13
0
ファイル: strutils.py プロジェクト: Rahul529/appoint
def bool_from_string(subject, strict=False, default=False):
    """Interpret a string as a boolean.

    A case-insensitive match is performed such that strings matching 't',
    'true', 'on', 'y', 'yes', or '1' are considered True and, when
    `strict=False`, anything else returns the value specified by 'default'.

    Useful for JSON-decoded stuff and config file parsing.

    If `strict=True`, unrecognized values, including None, will raise a
    ValueError which is useful when parsing values passed in from an API call.
    Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'.
    """
    if isinstance(subject, bool):
        return subject
    if not isinstance(subject, six.string_types):
        subject = six.text_type(subject)

    lowered = subject.strip().lower()

    if lowered in TRUE_STRINGS:
        return True
    elif lowered in FALSE_STRINGS:
        return False
    elif strict:
        acceptable = ', '.join(
            "'%s'" % s for s in sorted(TRUE_STRINGS + FALSE_STRINGS))
        msg = _("Unrecognized value '%(val)s', acceptable values are:"
                " %(acceptable)s") % {'val': subject,
                                      'acceptable': acceptable}
        raise ValueError(msg)
    else:
        return default
コード例 #14
0
def bool_from_string(subject, strict=False, default=False):
    """Interpret a string as a boolean.

    A case-insensitive match is performed such that strings matching 't',
    'true', 'on', 'y', 'yes', or '1' are considered True and, when
    `strict=False`, anything else returns the value specified by 'default'.

    Useful for JSON-decoded stuff and config file parsing.

    If `strict=True`, unrecognized values, including None, will raise a
    ValueError which is useful when parsing values passed in from an API call.
    Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'.
    """
    if isinstance(subject, bool):
        return subject
    if not isinstance(subject, six.string_types):
        subject = six.text_type(subject)

    lowered = subject.strip().lower()

    if lowered in TRUE_STRINGS:
        return True
    elif lowered in FALSE_STRINGS:
        return False
    elif strict:
        acceptable = ', '.join("'%s'" % s
                               for s in sorted(TRUE_STRINGS + FALSE_STRINGS))
        msg = _("Unrecognized value '%(val)s', acceptable values are:"
                " %(acceptable)s") % {
                    'val': subject,
                    'acceptable': acceptable
                }
        raise ValueError(msg)
    else:
        return default
コード例 #15
0
ファイル: strutils.py プロジェクト: Rahul529/appoint
def split_path(path, minsegs=1, maxsegs=None, rest_with_last=False):
    """Validate and split the given HTTP request path.

    **Examples**::

        ['a'] = _split_path('/a')
        ['a', None] = _split_path('/a', 1, 2)
        ['a', 'c'] = _split_path('/a/c', 1, 2)
        ['a', 'c', 'o/r'] = _split_path('/a/c/o/r', 1, 3, True)

    :param path: HTTP Request path to be split
    :param minsegs: Minimum number of segments to be extracted
    :param maxsegs: Maximum number of segments to be extracted
    :param rest_with_last: If True, trailing data will be returned as part
                           of last segment.  If False, and there is
                           trailing data, raises ValueError.
    :returns: list of segments with a length of maxsegs (non-existent
              segments will return as None)
    :raises: ValueError if given an invalid path

    .. versionadded:: 3.9
    """
    if not maxsegs:
        maxsegs = minsegs
    if minsegs > maxsegs:
        raise ValueError(_('minsegs > maxsegs: %(min)d > %(max)d)') %
                         {'min': minsegs, 'max': maxsegs})
    if rest_with_last:
        segs = path.split('/', maxsegs)
        minsegs += 1
        maxsegs += 1
        count = len(segs)
        if (segs[0] or count < minsegs or count > maxsegs or
                '' in segs[1:minsegs]):
            raise ValueError(_('Invalid path: %s') % urllib.parse.quote(path))
    else:
        minsegs += 1
        maxsegs += 1
        segs = path.split('/', maxsegs)
        count = len(segs)
        if (segs[0] or count < minsegs or count > maxsegs + 1 or
                '' in segs[1:minsegs] or
                (count == maxsegs + 1 and segs[maxsegs])):
            raise ValueError(_('Invalid path: %s') % urllib.parse.quote(path))
    segs = segs[1:maxsegs]
    segs.extend([None] * (maxsegs - 1 - len(segs)))
    return segs
コード例 #16
0
def convert_version_to_int(version):
    try:
        if isinstance(version, six.string_types):
            version = convert_version_to_tuple(version)
        if isinstance(version, tuple):
            return six.moves.reduce(lambda x, y: (x * 1000) + y, version)
    except Exception as ex:
        msg = _("Version %s is invalid.") % version
        six.raise_from(ValueError(msg), ex)
コード例 #17
0
    def delete(self, cluster_uuid):
        """Delete a Cluster."""
        if not os.path.exists(constants.SYSINV_RUNNING_IN_LAB):
            msg = _("Cluster cannot be deleted: %s")
            raise wsme.exc.ClientSideError(msg % cluster_uuid)

        cluster = self._get_one(cluster_uuid)
        self._check_allocated_peers(cluster)
        pecan.request.dbapi.cluster_destroy(cluster_uuid)
コード例 #18
0
def convert_version_to_int(version):
    try:
        if isinstance(version, six.string_types):
            version = convert_version_to_tuple(version)
        if isinstance(version, tuple):
            return six.moves.reduce(lambda x, y: (x * 1000) + y, version)
    except Exception as ex:
        msg = _("Version %s is invalid.") % version
        six.raise_from(ValueError(msg), ex)
コード例 #19
0
ファイル: strutils.py プロジェクト: hpcjmart/Openstack
def string_to_bytes(text, unit_system='IEC', return_int=False):
    """Converts a string into an float representation of bytes.

    The units supported for IEC ::

        Kb(it), Kib(it), Mb(it), Mib(it), Gb(it), Gib(it), Tb(it), Tib(it)
        KB, KiB, MB, MiB, GB, GiB, TB, TiB

    The units supported for SI ::

        kb(it), Mb(it), Gb(it), Tb(it)
        kB, MB, GB, TB

    Note that the SI unit system does not support capital letter 'K'

    :param text: String input for bytes size conversion.
    :param unit_system: Unit system for byte size conversion.
    :param return_int: If True, returns integer representation of text
                       in bytes. (default: decimal)
    :returns: Numerical representation of text in bytes.
    :raises ValueError: If text has an invalid value.

    """
    try:
        base, reg_ex = UNIT_SYSTEM_INFO[unit_system]
    except KeyError:
        msg = _('Invalid unit system: "%s"') % unit_system
        raise ValueError(msg)
    match = reg_ex.match(text)
    if match:
        magnitude = float(match.group(1))
        unit_prefix = match.group(2)
        if match.group(3) in ['b', 'bit']:
            magnitude /= 8
    else:
        msg = _('Invalid string format: %s') % text
        raise ValueError(msg)
    if not unit_prefix:
        res = magnitude
    else:
        res = magnitude * pow(base, UNIT_PREFIX_EXPONENT[unit_prefix])
    if return_int:
        return int(math.ceil(res))
    return res
コード例 #20
0
ファイル: strutils.py プロジェクト: Rahul529/appoint
def string_to_bytes(text, unit_system='IEC', return_int=False):
    """Converts a string into an float representation of bytes.

    The units supported for IEC ::

        Kb(it), Kib(it), Mb(it), Mib(it), Gb(it), Gib(it), Tb(it), Tib(it)
        KB, KiB, MB, MiB, GB, GiB, TB, TiB

    The units supported for SI ::

        kb(it), Mb(it), Gb(it), Tb(it)
        kB, MB, GB, TB

    Note that the SI unit system does not support capital letter 'K'

    :param text: String input for bytes size conversion.
    :param unit_system: Unit system for byte size conversion.
    :param return_int: If True, returns integer representation of text
                       in bytes. (default: decimal)
    :returns: Numerical representation of text in bytes.
    :raises ValueError: If text has an invalid value.

    """
    try:
        base, reg_ex = UNIT_SYSTEM_INFO[unit_system]
    except KeyError:
        msg = _('Invalid unit system: "%s"') % unit_system
        raise ValueError(msg)
    match = reg_ex.match(text)
    if match:
        magnitude = float(match.group(1))
        unit_prefix = match.group(2)
        if match.group(3) in ['b', 'bit']:
            magnitude /= 8
    else:
        msg = _('Invalid string format: %s') % text
        raise ValueError(msg)
    if not unit_prefix:
        res = magnitude
    else:
        res = magnitude * pow(base, UNIT_PREFIX_EXPONENT[unit_prefix])
    if return_int:
        return int(math.ceil(res))
    return res
コード例 #21
0
    def patch(self, cluster_uuid, patch):
        """Updates attributes of a Cluster."""
        if not os.path.exists(constants.SYSINV_RUNNING_IN_LAB):
            msg = _("Cluster attributes cannot be modified: %s")
            raise wsme.exc.ClientSideError(msg % patch.path)

        cluster = self._get_one(cluster_uuid)
        updates = self._get_updates(patch)
        self._validate_updates(cluster, updates)
        return pecan.request.dbapi.cluster_update(cluster_uuid, updates)
コード例 #22
0
 def copy_patch_to_version_vault(self, patch):
     versioned_vault = CONF.patching.patch_vault + \
         self.get_patch_sw_version(patch)
     if not os.path.isdir(versioned_vault):
         os.makedirs(versioned_vault)
     try:
         shutil.copy(patch, versioned_vault)
     except shutil.Error:
         msg = _("Unable to store patch file (%s)") % patch
         LOG.error(msg)
         raise webob.exc.HTTPUnprocessableEntity(explanation=msg)
コード例 #23
0
ファイル: alarm.py プロジェクト: starlingx/fault
    def delete(self, id):
        """Delete an alarm.

        :param id: uuid of an alarm.
        """
        data = pecan.request.dbapi.alarm_get(id)
        if data is None:
            raise wsme.exc.ClientSideError(_("can not find record to clear!"))
        pecan.request.dbapi.alarm_destroy(id)
        alarm_state = fm_constants.FM_ALARM_STATE_CLEAR
        tmp_dict = data.as_dict()
        self._alarm_save2event_log(tmp_dict, alarm_state, empty_uuid=True)
コード例 #24
0
    def get_patch_sw_version(self, filename):
        abs_patch = os.path.abspath(filename)
        try:
            PatchFile.read_patch(abs_patch, metadata_only=True)
            patch_data = PatchData()
            patch_id = patch_data.parse_metadata(self.PATCH_META_DATA)
            sw_version = patch_data.query_line(patch_id, self.SOFTWARE_VERSION)
        except PatchValidationFailure:
            msg = _("Patch validation failed during extraction")
            LOG.exception(msg)
            raise webob.exc.HTTPUnprocessableEntity(explanation=msg)
        except PatchMismatchFailure:
            msg = _("Patch Mismatch during extraction")
            LOG.exception(msg)
            raise webob.exc.HTTPUnprocessableEntity(explanation=msg)
        except tarfile.TarError:
            msg = _("Failed during patch extraction")
            LOG.exception(msg)
            raise webob.exc.HTTPUnprocessableEntity(explanation=msg)

        return sw_version
コード例 #25
0
ファイル: imageutils.py プロジェクト: JianyuWang/oslo.utils
 def _extract_bytes(self, details):
     # Replace it with the byte amount
     real_size = self.SIZE_RE.search(details)
     if not real_size:
         raise ValueError(_('Invalid input value "%s".') % details)
     magnitude = real_size.group(1)
     unit_of_measure = real_size.group(2)
     bytes_info = real_size.group(3)
     if bytes_info:
         return int(real_size.group(4))
     elif not unit_of_measure:
         return int(magnitude)
     return strutils.string_to_bytes('%s%sB' % (magnitude, unit_of_measure),
                                     return_int=True)
コード例 #26
0
 def _extract_bytes(self, details):
     # Replace it with the byte amount
     real_size = self.SIZE_RE.search(details)
     if not real_size:
         raise ValueError(_('Invalid input value "%s".') % details)
     magnitude = real_size.group(1)
     unit_of_measure = real_size.group(2)
     bytes_info = real_size.group(3)
     if bytes_info:
         return int(real_size.group(4))
     elif not unit_of_measure:
         return int(magnitude)
     return strutils.string_to_bytes('%s%sB' % (magnitude, unit_of_measure),
                                     return_int=True)
コード例 #27
0
ファイル: versionutils.py プロジェクト: openstack/oslo.utils
def convert_version_to_int(version):
    """Convert a version to an integer.

    *version* must be a string with dots or a tuple of integers.

    .. versionadded:: 2.0
    """
    try:
        if isinstance(version, six.string_types):
            version = convert_version_to_tuple(version)
        if isinstance(version, tuple):
            return six.moves.reduce(lambda x, y: (x * 1000) + y, version)
    except Exception as ex:
        msg = _("Version %s is invalid.") % version
        six.raise_from(ValueError(msg), ex)
コード例 #28
0
def convert_version_to_int(version):
    """Convert a version to an integer.

    *version* must be a string with dots or a tuple of integers.

    .. versionadded:: 2.0
    """
    try:
        if isinstance(version, str):
            version = convert_version_to_tuple(version)
        if isinstance(version, tuple):
            return functools.reduce(lambda x, y: (x * 1000) + y, version)
    except Exception as ex:
        msg = _("Version %s is invalid.") % version
        raise ValueError(msg) from ex
コード例 #29
0
    def _dispatch(self, req):
        """Called by self._router after matching the incoming request to a

        route and putting the information into req.environ.
        """

        match = req.environ['wsgiorg.routing_args'][1]
        if not match:
            if self.forwarder:
                return self.forwarder
            msg = _('The request is not allowed in System Controller')
            raise webob.exc.HTTPForbidden(explanation=msg)
        LOG.debug("Found match action!")
        app = match['controller']
        return app
コード例 #30
0
ファイル: imageutils.py プロジェクト: NeCTAR-RC/oslo.utils
 def _extract_details(self, root_cmd, root_details, lines_after):
     real_details = root_details
     if root_cmd == 'backing_file':
         # Replace it with the real backing file
         backing_match = self.BACKING_FILE_RE.match(root_details)
         if backing_match:
             real_details = backing_match.group(2).strip()
     elif root_cmd in ['virtual_size', 'cluster_size', 'disk_size']:
         # Replace it with the byte amount (if we can convert it)
         if root_details in ('None', 'unavailable'):
             real_details = 0
         else:
             real_details = self._extract_bytes(root_details)
     elif root_cmd == 'file_format':
         real_details = real_details.strip().lower()
     elif root_cmd == 'snapshot_list':
         # Next line should be a header, starting with 'ID'
         if not lines_after or not lines_after.pop(0).startswith("ID"):
             msg = _("Snapshot list encountered but no header found!")
             raise ValueError(msg)
         real_details = []
         # This is the sprintf pattern we will try to match
         # "%-10s%-20s%7s%20s%15s"
         # ID TAG VM SIZE DATE VM CLOCK (current header)
         while lines_after:
             line = lines_after[0]
             line_pieces = line.split()
             if len(line_pieces) != 6:
                 break
             # Check against this pattern in the final position
             # "%02d:%02d:%02d.%03d"
             date_pieces = line_pieces[5].split(":")
             if len(date_pieces) != 3:
                 break
             lines_after.pop(0)
             real_details.append({
                 'id':
                 line_pieces[0],
                 'tag':
                 line_pieces[1],
                 'vm_size':
                 line_pieces[2],
                 'date':
                 line_pieces[3],
                 'vm_clock':
                 line_pieces[4] + " " + line_pieces[5],
             })
     return real_details
コード例 #31
0
 def _extract_bytes(self, details):
     # Replace it with the byte amount
     real_size = self.SIZE_RE.search(details)
     if not real_size:
         raise ValueError(_('Invalid input value "%s".') % details)
     magnitude = real_size.group(1)
     unit_of_measure = real_size.group(2)
     bytes_info = real_size.group(3)
     if bytes_info:
         return int(real_size.group(4))
     elif not unit_of_measure:
         return int(magnitude)
     # Allow abbreviated unit such as K to mean KB for compatibility.
     if len(unit_of_measure) == 1 and unit_of_measure != 'B':
         unit_of_measure += 'B'
     return strutils.string_to_bytes('%s%s' % (magnitude, unit_of_measure),
                                     return_int=True)
コード例 #32
0
ファイル: imageutils.py プロジェクト: JianyuWang/oslo.utils
 def _extract_details(self, root_cmd, root_details, lines_after):
     real_details = root_details
     if root_cmd == 'backing_file':
         # Replace it with the real backing file
         backing_match = self.BACKING_FILE_RE.match(root_details)
         if backing_match:
             real_details = backing_match.group(2).strip()
     elif root_cmd in ['virtual_size', 'cluster_size', 'disk_size']:
         # Replace it with the byte amount (if we can convert it)
         if root_details in ('None', 'unavailable'):
             real_details = 0
         else:
             real_details = self._extract_bytes(root_details)
     elif root_cmd == 'file_format':
         real_details = real_details.strip().lower()
     elif root_cmd == 'snapshot_list':
         # Next line should be a header, starting with 'ID'
         if not lines_after or not lines_after.pop(0).startswith("ID"):
             msg = _("Snapshot list encountered but no header found!")
             raise ValueError(msg)
         real_details = []
         # This is the sprintf pattern we will try to match
         # "%-10s%-20s%7s%20s%15s"
         # ID TAG VM SIZE DATE VM CLOCK (current header)
         while lines_after:
             line = lines_after[0]
             line_pieces = line.split()
             if len(line_pieces) != 6:
                 break
             # Check against this pattern in the final position
             # "%02d:%02d:%02d.%03d"
             date_pieces = line_pieces[5].split(":")
             if len(date_pieces) != 3:
                 break
             lines_after.pop(0)
             real_details.append({
                 'id': line_pieces[0],
                 'tag': line_pieces[1],
                 'vm_size': line_pieces[2],
                 'date': line_pieces[3],
                 'vm_clock': line_pieces[4] + " " + line_pieces[5],
             })
     return real_details
コード例 #33
0
class ApiError(Exception):

    message = _("An unknown exception occurred.")

    # 500 - HTTPInternalServerError
    code = webob.exc.HTTPInternalServerError.code

    def __init__(self, message=None, **kwargs):

        self.kwargs = kwargs

        if 'code' not in self.kwargs and hasattr(self, 'code'):
            self.kwargs['code'] = self.code

        if message:
            self.message = message

        try:
            super(ApiError, self).__init__(self.message % kwargs)
            self.message = self.message % kwargs
        except Exception:
            LOG.exception(
                'Exception in string format operation, '
                'kwargs: %s', kwargs)
            raise

    def __str__(self):
        return repr(self.value)

    def __unicode__(self):
        return self.message

    def format_message(self):
        if self.__class__.__name__.endswith('_Remote'):
            return self.args[0]
        else:
            return six.text_type(self)
コード例 #34
0
 def _validate_zero_network(cls, network, prefix):
     data = netaddr.IPNetwork(network + "/" + str(prefix))
     network = data.network
     if network.value == 0:
         raise ValueError(_("Network must not be null"))
コード例 #35
0
ファイル: strutils.py プロジェクト: openstack/oslo.utils
def string_to_bytes(text, unit_system='IEC', return_int=False):
    """Converts a string into an float representation of bytes.

    The units supported for IEC / mixed::

        Kb(it), Kib(it), Mb(it), Mib(it), Gb(it), Gib(it), Tb(it), Tib(it)
        KB, KiB, MB, MiB, GB, GiB, TB, TiB

    The units supported for SI ::

        kb(it), Mb(it), Gb(it), Tb(it)
        kB, MB, GB, TB

    SI units are interpreted as power-of-ten (e.g. 1kb = 1000b).  Note
    that the SI unit system does not support capital letter 'K'

    IEC units are interpreted as power-of-two (e.g. 1MiB = 1MB =
    1024b)

    Mixed units interpret the "i" to mean IEC, and no "i" to mean SI
    (e.g. 1kb = 1000b, 1kib == 1024b).  Additionaly, mixed units
    interpret 'K' as power-of-ten.  This mode is not particuarly
    useful for new code, but can help with compatability for parsers
    such as GNU parted.

    :param text: String input for bytes size conversion.
    :param unit_system: Unit system for byte size conversion.
    :param return_int: If True, returns integer representation of text
                       in bytes. (default: decimal)
    :returns: Numerical representation of text in bytes.
    :raises ValueError: If text has an invalid value.

    """
    try:
        base, reg_ex = UNIT_SYSTEM_INFO[unit_system]
    except KeyError:
        msg = _('Invalid unit system: "%s"') % unit_system
        raise ValueError(msg)
    match = reg_ex.match(text)
    if match:
        magnitude = float(match.group(1))
        unit_prefix = match.group(2)
        if match.group(3) in ['b', 'bit']:
            magnitude /= 8

        # In the mixed matcher, IEC units (with a trailing 'i') are
        # interpreted as power-of-two, others as power-of-ten
        if unit_system == 'mixed':
            if unit_prefix and not unit_prefix.endswith('i'):
                # For maximum compatability in mixed mode, we understand
                # "K" (which is not strict SI) as "k"
                if unit_prefix.startswith == 'K':
                    unit_prefix = 'k'
                base = 1000
            else:
                base = 1024
    else:
        msg = _('Invalid string format: %s') % text
        raise ValueError(msg)

    if not unit_prefix:
        res = magnitude
    else:
        res = magnitude * pow(base, UNIT_PREFIX_EXPONENT[unit_prefix])
    if return_int:
        return int(math.ceil(res))
    return res
コード例 #36
0
 def _validate_name(cls, name):
     if len(name) < 1:
         raise ValueError(_("Name must not be an empty string"))
コード例 #37
0
 def _validate_prefix(cls, prefix):
     if prefix < 1:
         raise ValueError(_("Address prefix must be greater than 1"))
コード例 #38
0
 def _validate_network_type(cls, network):
     address = netaddr.IPAddress(network)
     if not address.is_unicast() and not address.is_multicast():
         raise ValueError(
             _("Network address must be a unicast address or"
               "a multicast address"))
コード例 #39
0
 def _validate_allocation_order(cls, order):
     if order and order not in VALID_ALLOCATION_ORDER:
         raise ValueError(
             _("Network address allocation order must be one "
               "of: %s") % ', '.join(VALID_ALLOCATION_ORDER))
コード例 #40
0
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#

# vim: tabstop=4 shiftwidth=4 softtabstop=4

# All Rights Reserved.
#

from oslo_config import cfg
from oslo_utils._i18n import _

INVENTORY_LLDP_OPTS = [
    cfg.ListOpt('drivers',
                default=['lldpd'],
                help=_("An ordered list of inventory LLDP driver "
                       "entrypoints to be loaded from the "
                       "inventory.agent namespace.")),
]

cfg.CONF.register_opts(INVENTORY_LLDP_OPTS, group="lldp")
コード例 #41
0
def string_to_bytes(text, unit_system='IEC', return_int=False):
    """Converts a string into an float representation of bytes.

    The units supported for IEC / mixed::

        Kb(it), Kib(it), Mb(it), Mib(it), Gb(it), Gib(it), Tb(it), Tib(it)
        KB, KiB, MB, MiB, GB, GiB, TB, TiB

    The units supported for SI ::

        kb(it), Mb(it), Gb(it), Tb(it)
        kB, MB, GB, TB

    SI units are interpreted as power-of-ten (e.g. 1kb = 1000b).  Note
    that the SI unit system does not support capital letter 'K'

    IEC units are interpreted as power-of-two (e.g. 1MiB = 1MB =
    1024b)

    Mixed units interpret the "i" to mean IEC, and no "i" to mean SI
    (e.g. 1kb = 1000b, 1kib == 1024b).  Additionaly, mixed units
    interpret 'K' as power-of-ten.  This mode is not particuarly
    useful for new code, but can help with compatability for parsers
    such as GNU parted.

    :param text: String input for bytes size conversion.
    :param unit_system: Unit system for byte size conversion.
    :param return_int: If True, returns integer representation of text
                       in bytes. (default: decimal)
    :returns: Numerical representation of text in bytes.
    :raises ValueError: If text has an invalid value.

    """
    try:
        base, reg_ex = UNIT_SYSTEM_INFO[unit_system]
    except KeyError:
        msg = _('Invalid unit system: "%s"') % unit_system
        raise ValueError(msg)
    match = reg_ex.match(text)
    if match:
        magnitude = float(match.group(1))
        unit_prefix = match.group(2)
        if match.group(3) in ['b', 'bit']:
            magnitude /= 8

        # In the mixed matcher, IEC units (with a trailing 'i') are
        # interpreted as power-of-two, others as power-of-ten
        if unit_system == 'mixed':
            if unit_prefix and not unit_prefix.endswith('i'):
                # For maximum compatability in mixed mode, we understand
                # "K" (which is not strict SI) as "k"
                if unit_prefix.startswith == 'K':
                    unit_prefix = 'k'
                base = 1000
            else:
                base = 1024
    else:
        msg = _('Invalid string format: %s') % text
        raise ValueError(msg)

    if not unit_prefix:
        res = magnitude
    else:
        res = magnitude * pow(base, UNIT_PREFIX_EXPONENT[unit_prefix])
    if return_int:
        return int(math.ceil(res))
    return res