Esempio n. 1
0
def to_bytes(text, default=0):
    """Converts a string into an integer of bytes.

    Looks at the last characters of the text to determine
    what conversion is needed to turn the input text into a byte number.
    Supports "B, K(B), M(B), G(B), and T(B)". (case insensitive)

    :param text: String input for bytes size conversion.
    :param default: Default return value when text is blank.

    """
    match = BYTE_REGEX.search(text)
    if match:
        magnitude = int(match.group(1))
        mult_key_org = match.group(2)
        if not mult_key_org:
            return magnitude
    elif text:
        msg = _('Invalid string format: %s') % text
        raise TypeError(msg)
    else:
        return default
    mult_key = mult_key_org.lower().replace('b', '', 1)
    multiplier = BYTE_MULTIPLIERS.get(mult_key)
    if multiplier is None:
        msg = _('Unknown byte multiplier: %s') % mult_key_org
        raise TypeError(msg)
    return magnitude * multiplier
Esempio n. 2
0
def bool_from_string(subject, strict=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 is considered False.

    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 not isinstance(subject, basestring):
        subject = str(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 False
Esempio n. 3
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 not isinstance(subject, six.string_types):
        subject = str(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
Esempio n. 4
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 ::

        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
Esempio n. 5
0
    def _get_endpoint_and_token(self, args, force_auth=False):
        image_url = self._get_image_url(args)
        auth_token = args.os_auth_token

        auth_reqd = force_auth or (utils.is_authentication_required(args.func)
                                   and not (auth_token and image_url))

        if not auth_reqd:
            endpoint = image_url
            token = args.os_auth_token
        else:

            if not args.os_username:
                raise exc.CommandError(
                    _("You must provide a username via"
                      " either --os-username or "
                      "env[OS_USERNAME]"))

            if not args.os_password:
                raise exc.CommandError(
                    _("You must provide a password via"
                      " either --os-password or "
                      "env[OS_PASSWORD]"))

            # Validate password flow auth
            project_info = (args.os_tenant_name or
                            args.os_tenant_id or
                            (args.os_project_name and
                            (args.project_domain_name or
                                args.project_domain_id)) or
                            args.os_project_id)

            if (not project_info):
                # tenent is deprecated in Keystone v3. Use the latest
                # terminology instead.
                raise exc.CommandError(
                    _("You must provide a project_id or project_name ("
                      "with project_domain_name or project_domain_id) "
                      "via "
                      "  --os-project-id (env[OS_PROJECT_ID])"
                      "  --os-project-name (env[OS_PROJECT_NAME]),"
                      "  --os-project-domain-id "
                      "(env[OS_PROJECT_DOMAIN_ID])"
                      "  --os-project-domain-name "
                      "(env[OS_PROJECT_DOMAIN_NAME])"))

            if not args.os_auth_url:
                raise exc.CommandError(
                    _("You must provide an auth url via"
                      " either --os-auth-url or "
                      "via env[OS_AUTH_URL]"))

            kwargs = {
                'auth_url': args.os_auth_url,
                'username': args.os_username,
                'user_id': args.os_user_id,
                'user_domain_id': args.os_user_domain_id,
                'user_domain_name': args.os_user_domain_name,
                'password': args.os_password,
                'tenant_name': args.os_tenant_name,
                'tenant_id': args.os_tenant_id,
                'project_name': args.os_project_name,
                'project_id': args.os_project_id,
                'project_domain_name': args.os_project_domain_name,
                'project_domain_id': args.os_project_domain_id,
                'insecure': args.insecure,
                'cacert': args.os_cacert,
                'cert': args.os_cert,
                'key': args.os_key
            }
            ks_session = self._get_keystone_session(**kwargs)
            token = args.os_auth_token or ks_session.get_token()

            endpoint_type = args.os_endpoint_type or 'public'
            service_type = args.os_service_type or 'image'
            endpoint = args.os_image_url or ks_session.get_endpoint(
                service_type=service_type,
                interface=endpoint_type,
                region_name=args.os_region_name)

        return endpoint, token
Esempio n. 6
0
    def _get_endpoint_and_token(self, args, force_auth=False):
        image_url = self._get_image_url(args)
        auth_token = args.os_auth_token

        auth_reqd = force_auth or (utils.is_authentication_required(args.func)
                                   and not (auth_token and image_url))

        if not auth_reqd:
            endpoint = image_url
            token = args.os_auth_token
        else:

            if not args.os_username:
                raise exc.CommandError(
                    _("You must provide a username via"
                      " either --os-username or "
                      "env[OS_USERNAME]"))

            if not args.os_password:
                # No password, If we've got a tty, try prompting for it
                if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():
                    # Check for Ctl-D
                    try:
                        args.os_password = getpass.getpass('OS Password: '******'t have a tty or the
                # user Ctl-D when prompted.
                if not args.os_password:
                    raise exc.CommandError(
                        _("You must provide a password via "
                          "either --os-password, "
                          "env[OS_PASSWORD], "
                          "or prompted response"))

            # Validate password flow auth
            project_info = (args.os_tenant_name or
                            args.os_tenant_id or
                            (args.os_project_name and
                            (args.os_project_domain_name or
                                args.os_project_domain_id)) or
                            args.os_project_id)

            if (not project_info):
                # tenant is deprecated in Keystone v3. Use the latest
                # terminology instead.
                raise exc.CommandError(
                    _("You must provide a project_id or project_name ("
                      "with project_domain_name or project_domain_id) "
                      "via "
                      "  --os-project-id (env[OS_PROJECT_ID])"
                      "  --os-project-name (env[OS_PROJECT_NAME]),"
                      "  --os-project-domain-id "
                      "(env[OS_PROJECT_DOMAIN_ID])"
                      "  --os-project-domain-name "
                      "(env[OS_PROJECT_DOMAIN_NAME])"))

            if not args.os_auth_url:
                raise exc.CommandError(
                    _("You must provide an auth url via"
                      " either --os-auth-url or "
                      "via env[OS_AUTH_URL]"))

            kwargs = {
                'auth_url': args.os_auth_url,
                'username': args.os_username,
                'user_id': args.os_user_id,
                'user_domain_id': args.os_user_domain_id,
                'user_domain_name': args.os_user_domain_name,
                'password': args.os_password,
                'tenant_name': args.os_tenant_name,
                'tenant_id': args.os_tenant_id,
                'project_name': args.os_project_name,
                'project_id': args.os_project_id,
                'project_domain_name': args.os_project_domain_name,
                'project_domain_id': args.os_project_domain_id,
                'insecure': args.insecure,
                'cacert': args.os_cacert,
                'cert': args.os_cert,
                'key': args.os_key
            }
            ks_session = self._get_keystone_session(**kwargs)
            token = args.os_auth_token or ks_session.get_token()

            endpoint_type = args.os_endpoint_type or 'public'
            service_type = args.os_service_type or 'image'
            endpoint = args.os_image_url or ks_session.get_endpoint(
                service_type=service_type,
                interface=endpoint_type,
                region_name=args.os_region_name)

        return endpoint, token
Esempio n. 7
0
    def _get_endpoint_and_token(self, args, force_auth=False):
        image_url = self._get_image_url(args)
        auth_token = args.os_auth_token

        auth_reqd = force_auth or (utils.is_authentication_required(args.func)
                                   and not (auth_token and image_url))

        if not auth_reqd:
            endpoint = image_url
            token = args.os_auth_token
        else:

            if not args.os_username:
                raise exc.CommandError(
                    _("You must provide a username via"
                      " either --os-username or "
                      "env[OS_USERNAME]"))

            if not args.os_password:
                # No password, If we've got a tty, try prompting for it
                if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():
                    # Check for Ctl-D
                    try:
                        args.os_password = getpass.getpass('OS Password: '******'t have a tty or the
                # user Ctl-D when prompted.
                if not args.os_password:
                    raise exc.CommandError(
                        _("You must provide a password via "
                          "either --os-password, "
                          "env[OS_PASSWORD], "
                          "or prompted response"))

            # Validate password flow auth
            project_info = (args.os_tenant_name or
                            args.os_tenant_id or
                            (args.os_project_name and
                            (args.os_project_domain_name or
                                args.os_project_domain_id)) or
                            args.os_project_id)

            if (not project_info):
                # tenant is deprecated in Keystone v3. Use the latest
                # terminology instead.
                raise exc.CommandError(
                    _("You must provide a project_id or project_name ("
                      "with project_domain_name or project_domain_id) "
                      "via "
                      "  --os-project-id (env[OS_PROJECT_ID])"
                      "  --os-project-name (env[OS_PROJECT_NAME]),"
                      "  --os-project-domain-id "
                      "(env[OS_PROJECT_DOMAIN_ID])"
                      "  --os-project-domain-name "
                      "(env[OS_PROJECT_DOMAIN_NAME])"))

            if not args.os_auth_url:
                raise exc.CommandError(
                    _("You must provide an auth url via"
                      " either --os-auth-url or "
                      "via env[OS_AUTH_URL]"))

            kwargs = {
                'auth_url': args.os_auth_url,
                'username': args.os_username,
                'user_id': args.os_user_id,
                'user_domain_id': args.os_user_domain_id,
                'user_domain_name': args.os_user_domain_name,
                'password': args.os_password,
                'tenant_name': args.os_tenant_name,
                'tenant_id': args.os_tenant_id,
                'project_name': args.os_project_name,
                'project_id': args.os_project_id,
                'project_domain_name': args.os_project_domain_name,
                'project_domain_id': args.os_project_domain_id,
                'insecure': args.insecure,
                'cacert': args.os_cacert,
                'cert': args.os_cert,
                'key': args.os_key
            }
            ks_session = self._get_keystone_session(**kwargs)
            token = args.os_auth_token or ks_session.get_token()

            endpoint_type = args.os_endpoint_type or 'public'
            service_type = args.os_service_type or 'image'
            endpoint = args.os_image_url or ks_session.get_endpoint(
                service_type=service_type,
                interface=endpoint_type,
                region_name=args.os_region_name)

        return endpoint, token
Esempio n. 8
0
    def _get_endpoint_and_token(self, args, force_auth=False):
        image_url = self._get_image_url(args)
        auth_token = args.os_auth_token

        auth_reqd = force_auth or (utils.is_authentication_required(args.func)
                                   and not (auth_token and image_url))

        if not auth_reqd:
            endpoint = image_url
            token = args.os_auth_token
        else:

            if not args.os_username:
                raise exc.CommandError(
                    _("You must provide a username via"
                      " either --os-username or "
                      "env[OS_USERNAME]"))

            if not args.os_password:
                raise exc.CommandError(
                    _("You must provide a password via"
                      " either --os-password or "
                      "env[OS_PASSWORD]"))

            # Validate password flow auth
            project_info = (
                args.os_tenant_name or args.os_tenant_id
                or (args.os_project_name and
                    (args.project_domain_name or args.project_domain_id))
                or args.os_project_id)

            if (not project_info):
                # tenent is deprecated in Keystone v3. Use the latest
                # terminology instead.
                raise exc.CommandError(
                    _("You must provide a project_id or project_name ("
                      "with project_domain_name or project_domain_id) "
                      "via "
                      "  --os-project-id (env[OS_PROJECT_ID])"
                      "  --os-project-name (env[OS_PROJECT_NAME]),"
                      "  --os-project-domain-id "
                      "(env[OS_PROJECT_DOMAIN_ID])"
                      "  --os-project-domain-name "
                      "(env[OS_PROJECT_DOMAIN_NAME])"))

            if not args.os_auth_url:
                raise exc.CommandError(
                    _("You must provide an auth url via"
                      " either --os-auth-url or "
                      "via env[OS_AUTH_URL]"))

            kwargs = {
                'auth_url': args.os_auth_url,
                'username': args.os_username,
                'user_id': args.os_user_id,
                'user_domain_id': args.os_user_domain_id,
                'user_domain_name': args.os_user_domain_name,
                'password': args.os_password,
                'tenant_name': args.os_tenant_name,
                'tenant_id': args.os_tenant_id,
                'project_name': args.os_project_name,
                'project_id': args.os_project_id,
                'project_domain_name': args.os_project_domain_name,
                'project_domain_id': args.os_project_domain_id,
                'insecure': args.insecure,
                'cacert': args.os_cacert,
                'cert': args.os_cert,
                'key': args.os_key
            }
            ks_session = self._get_keystone_session(**kwargs)
            token = args.os_auth_token or ks_session.get_token()

            endpoint_type = args.os_endpoint_type or 'public'
            service_type = args.os_service_type or 'image'
            endpoint = args.os_image_url or ks_session.get_endpoint(
                service_type=service_type,
                endpoint_type=endpoint_type,
                region_name=args.os_region_name)

        return endpoint, token