Python oslo_utils.strutils.bool_from_string() Examples

The following are 30 code examples of oslo_utils.strutils.bool_from_string(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_utils.strutils , or try the search function .
Example #1
Source File: base_models.py    From octavia with Apache License 2.0 6 votes vote down vote up
def apply_filter(query, model, filters):
        translated_filters = {}
        child_map = {}
        # Convert enabled to proper type
        if 'enabled' in filters:
            filters['enabled'] = strutils.bool_from_string(
                filters['enabled'])
        for attr, name_map in model.__v2_wsme__._child_map.items():
            for k, v in name_map.items():
                if attr in filters and k in filters[attr]:
                    child_map.setdefault(attr, {}).update(
                        {k: filters[attr].pop(k)})
            filters.pop(attr, None)

        for k, v in model.__v2_wsme__._type_to_model_map.items():
            if k in filters:
                translated_filters[v] = filters.pop(k)
        translated_filters.update(filters)
        if translated_filters:
            query = query.filter_by(**translated_filters)
        for k, v in child_map.items():
            query = query.join(getattr(model, k)).filter_by(**v)
        return query 
Example #2
Source File: count.py    From vitrage with Apache License 2.0 6 votes vote down vote up
def get(self, all_tenants=False):
        all_tenants = bool_from_string(all_tenants)
        if all_tenants:
            enforce("get alarms count:all_tenants", pecan.request.headers,
                    pecan.request.enforcer, {})
        else:
            enforce("get alarms count", pecan.request.headers,
                    pecan.request.enforcer, {})

        LOG.info('received get alarm counts')

        try:
            alarm_counts_json = pecan.request.client.call(
                pecan.request.context, 'get_alarm_counts',
                all_tenants=all_tenants)

            return json.loads(alarm_counts_json)

        except Exception:
            LOG.exception('failed to get alarm count.')
            abort(404, 'Failed to get alarm count.') 
Example #3
Source File: utils.py    From manila with Apache License 2.0 6 votes vote down vote up
def get_bool_from_api_params(key, params, default=False, strict=True):
    """Parse bool value from request params.

    HTTPBadRequest will be directly raised either of the cases below:
    1. invalid bool string was found by key(with strict on).
    2. key not found while default value is invalid(with strict on).
    """
    param = params.get(key, default)
    try:
        param = strutils.bool_from_string(param,
                                          strict=strict,
                                          default=default)
    except ValueError:
        msg = _('Invalid value %(param)s for %(param_string)s. '
                'Expecting a boolean.') % {'param': param,
                                           'param_string': key}
        raise exc.HTTPBadRequest(explanation=msg)
    return param 
Example #4
Source File: utils.py    From manila with Apache License 2.0 6 votes vote down vote up
def is_all_tenants(search_opts):
    """Checks to see if the all_tenants flag is in search_opts

    :param dict search_opts: The search options for a request
    :returns: boolean indicating if all_tenants are being requested or not
    """
    all_tenants = search_opts.get('all_tenants')
    if all_tenants:
        try:
            all_tenants = strutils.bool_from_string(all_tenants, True)
        except ValueError as err:
            raise exception.InvalidInput(six.text_type(err))
    else:
        # The empty string is considered enabling all_tenants
        all_tenants = 'all_tenants' in search_opts
    return all_tenants 
Example #5
Source File: cliutils.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_password(max_password_prompts=3):
    """Read password from TTY."""
    verify = strutils.bool_from_string(env("OS_VERIFY_PASSWORD"))
    pw = None
    if hasattr(sys.stdin, "isatty") and sys.stdin.isatty():
        # Check for Ctrl-D
        try:
            for __ in moves.range(max_password_prompts):
                pw1 = getpass.getpass("OS Password: ")
                if verify:
                    pw2 = getpass.getpass("Please verify: ")
                else:
                    pw2 = pw1
                if pw1 == pw2 and pw1:
                    pw = pw1
                    break
        except EOFError:
            pass
    return pw 
Example #6
Source File: __init__.py    From searchlight with Apache License 2.0 6 votes vote down vote up
def fix_greendns_ipv6():
    if dnspython_installed:
        # All of this is because if dnspython is present in your environment
        # then eventlet monkeypatches socket.getaddrinfo() with an
        # implementation which doesn't work for IPv6. What we're checking here
        # is that the magic environment variable was set when the import
        # happened.
        nogreendns = 'EVENTLET_NO_GREENDNS'
        flag = os.environ.get(nogreendns, '')
        if 'eventlet' in sys.modules and not strutils.bool_from_string(flag):
            msg = _("It appears that the eventlet module has been "
                    "imported prior to setting %s='yes'. It is currently "
                    "necessary to disable eventlet.greendns "
                    "if using ipv6 since eventlet.greendns currently "
                    "breaks with ipv6 addresses. Please ensure that "
                    "eventlet is not imported prior to this being set.")
            raise ImportError(msg % (nogreendns))

        os.environ[nogreendns] = 'yes' 
Example #7
Source File: share_types.py    From manila with Apache License 2.0 6 votes vote down vote up
def _parse_is_public(is_public):
        """Parse is_public into something usable.

        * True: API should list public share types only
        * False: API should list private share types only
        * None: API should list both public and private share types
        """
        if is_public is None:
            # preserve default value of showing only public types
            return True
        elif six.text_type(is_public).lower() == "all":
            return None
        else:
            try:
                return strutils.bool_from_string(is_public, strict=True)
            except ValueError:
                msg = _('Invalid is_public filter [%s]') % is_public
                raise exc.HTTPBadRequest(explanation=msg) 
Example #8
Source File: k8s_fedora_template_def.py    From magnum with Apache License 2.0 6 votes vote down vote up
def _set_cert_manager_params(self, context, cluster, extra_params):
        cert_manager_api = cluster.labels.get('cert_manager_api')
        if strutils.bool_from_string(cert_manager_api):
            extra_params['cert_manager_api'] = cert_manager_api
            ca_cert = cert_manager.get_cluster_ca_certificate(cluster,
                                                              context=context)
            if six.PY3 and isinstance(ca_cert.get_private_key_passphrase(),
                                      six.text_type):
                extra_params['ca_key'] = x509.decrypt_key(
                    ca_cert.get_private_key(),
                    ca_cert.get_private_key_passphrase().encode()
                ).decode().replace("\n", "\\n")
            else:
                extra_params['ca_key'] = x509.decrypt_key(
                    ca_cert.get_private_key(),
                    ca_cert.get_private_key_passphrase()).replace("\n", "\\n") 
Example #9
Source File: cliutils.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_password(max_password_prompts=3):
    """Read password from TTY."""
    verify = strutils.bool_from_string(env("OS_VERIFY_PASSWORD"))
    pw = None
    if hasattr(sys.stdin, "isatty") and sys.stdin.isatty():
        # Check for Ctrl-D
        try:
            for __ in moves.range(max_password_prompts):
                pw1 = getpass.getpass("OS Password: ")
                if verify:
                    pw2 = getpass.getpass("Please verify: ")
                else:
                    pw2 = pw1
                if pw1 == pw2 and pw1:
                    pw = pw1
                    break
        except EOFError:
            pass
    return pw 
Example #10
Source File: share_types.py    From manila with Apache License 2.0 6 votes vote down vote up
def parse_boolean_extra_spec(extra_spec_key, extra_spec_value):
    """Parse extra spec values of the form '<is> True' or '<is> False'

    This method returns the boolean value of an extra spec value.  If
    the value does not conform to the standard boolean pattern, it raises
    an InvalidExtraSpec exception.
    """
    if not isinstance(extra_spec_value, six.string_types):
        extra_spec_value = six.text_type(extra_spec_value)

    match = re.match(r'^<is>\s*(?P<value>True|False)$',
                     extra_spec_value.strip(),
                     re.IGNORECASE)
    if match:
        extra_spec_value = match.group('value')
    try:
        return strutils.bool_from_string(extra_spec_value, strict=True)
    except ValueError:
        msg = (_('Invalid boolean extra spec %(key)s : %(value)s') %
               {'key': extra_spec_key, 'value': extra_spec_value})
        raise exception.InvalidExtraSpec(reason=msg) 
Example #11
Source File: engine.py    From taskflow with Apache License 2.0 6 votes vote down vote up
def __init__(self, flow, flow_detail, backend, options):
        super(ActionEngine, self).__init__(flow, flow_detail, backend, options)
        self._runtime = None
        self._compiled = False
        self._compilation = None
        self._compiler = compiler.PatternCompiler(flow)
        self._lock = threading.RLock()
        self._storage_ensured = False
        self._validated = False
        # Retries are not *currently* executed out of the engines process
        # or thread (this could change in the future if we desire it to).
        self._retry_executor = executor.SerialRetryExecutor()
        self._inject_transient = strutils.bool_from_string(
            self._options.get('inject_transient', True))
        self._gather_statistics = strutils.bool_from_string(
            self._options.get('gather_statistics', True))
        self._statistics = {} 
Example #12
Source File: cliutils.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_password(max_password_prompts=3):
    """Read password from TTY."""
    verify = strutils.bool_from_string(env("OS_VERIFY_PASSWORD"))
    pw = None
    if hasattr(sys.stdin, "isatty") and sys.stdin.isatty():
        # Check for Ctrl-D
        try:
            for __ in moves.range(max_password_prompts):
                pw1 = getpass.getpass("OS Password: ")
                if verify:
                    pw2 = getpass.getpass("Please verify: ")
                else:
                    pw2 = pw1
                if pw1 == pw2 and pw1:
                    pw = pw1
                    break
        except EOFError:
            pass
    return pw 
Example #13
Source File: zun_services.py    From zun with Apache License 2.0 6 votes vote down vote up
def _update_forced_down(self, context, body):
        """Set or unset forced_down flag for the service"""
        try:
            forced_down = strutils.bool_from_string(body['forced_down'], True)
        except ValueError:
            bools = ', '.join(strutils.TRUE_STRINGS + strutils.FALSE_STRINGS)
            raise exception.InvalidValue(_('Valid forced_down values are: %s')
                                         % bools)
        self._update(context, body['host'], body['binary'],
                     {"forced_down": forced_down})
        res = {
            'service': {
                'host': body['host'],
                'binary': body['binary'],
                'forced_down': forced_down
            },
        }
        return res 
Example #14
Source File: objects.py    From os-net-config with Apache License 2.0 6 votes vote down vote up
def from_json(json):
        if json.get('next_hop') and json.get('nexthop'):
            msg = ('Invalid Route JSON object with both next_hop and nexthop '
                   'configured. Use either next_hop or nexthop.')
            raise InvalidConfigException(msg)

        if json.get('ip_netmask') and json.get('destination'):
            msg = ('Invalid Route JSON object with both ip_netmask and '
                   'destination configured. Use either ip_netmask or '
                   'destination.')
            raise InvalidConfigException(msg)

        next_hop = json.get('next_hop', json.get('nexthop'))
        if next_hop is None:
            msg = ('Route JSON objects require next_hop or nexthop to be '
                   'configured.')
            raise InvalidConfigException(msg)
        ip_netmask = json.get('ip_netmask', json.get('destination', ""))
        route_options = json.get('route_options', "")
        default = strutils.bool_from_string(str(json.get('default', False)))
        route_options = json.get('route_options', "")
        route_table = json.get('table', "")
        return Route(next_hop, ip_netmask, default, route_options, route_table) 
Example #15
Source File: images.py    From zun with Apache License 2.0 6 votes vote down vote up
def search(self, image, image_driver=None, exact_match=False):
        """Search a specific image

        :param image:  Name of the image.
        :param image_driver: Name of the image driver (glance, docker).
        :param exact_match: if True, exact match the image name.
        """
        context = pecan.request.context
        policy.enforce(context, "image:search",
                       action="image:search")
        LOG.debug('Calling compute.image_search with %s', image)
        try:
            exact_match = strutils.bool_from_string(exact_match, strict=True)
        except ValueError:
            bools = ', '.join(strutils.TRUE_STRINGS + strutils.FALSE_STRINGS)
            raise exception.InvalidValue(_('Valid exact_match values are: %s')
                                         % bools)
        # Valiadtion accepts 'None' so need to convert it to None
        image_driver = api_utils.string_or_none(image_driver)
        if not image_driver:
            image_driver = CONF.default_image_driver

        return pecan.request.compute_api.image_search(context, image,
                                                      image_driver,
                                                      exact_match, None) 
Example #16
Source File: client_cmode.py    From manila with Apache License 2.0 6 votes vote down vote up
def set_cluster_peer_policy(self, is_unauthenticated_access_permitted=None,
                                passphrase_minimum_length=None):
        """Modifies the cluster peering policy configuration."""

        if not self.features.CLUSTER_PEER_POLICY:
            return

        if (is_unauthenticated_access_permitted is None and
                passphrase_minimum_length is None):
            return

        api_args = {}
        if is_unauthenticated_access_permitted is not None:
            api_args['is-unauthenticated-access-permitted'] = (
                'true' if strutils.bool_from_string(
                    is_unauthenticated_access_permitted) else 'false')
        if passphrase_minimum_length is not None:
            api_args['passphrase-minlength'] = six.text_type(
                passphrase_minimum_length)

        self.send_request('cluster-peer-policy-modify', api_args) 
Example #17
Source File: webhook.py    From vitrage with Apache License 2.0 6 votes vote down vote up
def get_all(self, **kwargs):
        LOG.info('list all webhooks with args: %s', kwargs)

        all_tenants = kwargs.get(TenantProps.ALL_TENANTS, False)
        all_tenants = bool_from_string(all_tenants)

        if all_tenants:
            enforce('webhook list:all_tenants', pecan.request.headers,
                    pecan.request.enforcer, {})
        else:
            enforce('webhook list', pecan.request.headers,
                    pecan.request.enforcer, {})

        try:
            return self._get_all(all_tenants)
        except Exception:
            LOG.exception('Failed to list webhooks.')
            abort(404, 'Failed to list webhooks.') 
Example #18
Source File: cliutils.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_password(max_password_prompts=3):
    """Read password from TTY."""
    verify = strutils.bool_from_string(env("OS_VERIFY_PASSWORD"))
    pw = None
    if hasattr(sys.stdin, "isatty") and sys.stdin.isatty():
        # Check for Ctrl-D
        try:
            for __ in moves.range(max_password_prompts):
                pw1 = getpass.getpass("OS Password: ")
                if verify:
                    pw2 = getpass.getpass("Please verify: ")
                else:
                    pw2 = pw1
                if pw1 == pw2 and pw1:
                    pw = pw1
                    break
        except EOFError:
            pass
    return pw 
Example #19
Source File: utils.py    From manila with Apache License 2.0 5 votes vote down vote up
def use_thin_logic(share_type):
    # NOTE(xyang): To preserve the existing behavior, we use thin logic
    # to evaluate in two cases:
    # 1) 'thin_provisioning' is not set in extra specs (This is for
    #    backward compatibility. If not set, the scheduler behaves
    #    the same as before this bug fix).
    # 2) 'thin_provisioning' is set in extra specs and it is
    #    '<is> True' or 'True'.
    # Otherwise we use the thick logic to evaluate.
    use_thin_logic = True
    thin_spec = None
    try:
        thin_spec = share_type.get('extra_specs', {}).get(
            'thin_provisioning')
        if thin_spec is None:
            thin_spec = share_type.get('extra_specs', {}).get(
                'capabilities:thin_provisioning')
        # NOTE(xyang) 'use_thin_logic' and 'thin_provisioning' are NOT
        # the same thing. The first purpose of "use_thin_logic" is to
        # preserve the existing scheduler behavior if 'thin_provisioning'
        # is NOT in extra_specs (if thin_spec is None, use_thin_logic
        # should be True). The second purpose of 'use_thin_logic'
        # is to honor 'thin_provisioning' if it is in extra specs (if
        # thin_spec is set to True, use_thin_logic should be True; if
        # thin_spec is set to False, use_thin_logic should be False).
        use_thin_logic = strutils.bool_from_string(
            thin_spec, strict=True) if thin_spec is not None else True
    except ValueError:
        # Check if the value of thin_spec is '<is> True'.
        if thin_spec is not None and not extra_specs_ops.match(
                True, thin_spec):
            use_thin_logic = False
    return use_thin_logic 
Example #20
Source File: completer.py    From taskflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, runtime):
        self._runtime = weakref.proxy(runtime)
        self._storage = runtime.storage
        self._undefined_resolver = RevertAll(self._runtime)
        self._defer_reverts = strutils.bool_from_string(
            self._runtime.options.get('defer_reverts', False))
        self._resolve = not strutils.bool_from_string(
            self._runtime.options.get('never_resolve', False)) 
Example #21
Source File: extra_specs_ops.py    From manila with Apache License 2.0 5 votes vote down vote up
def match(value, req):
    # Make case-insensitive
    if (isinstance(value, six.string_types)):
        value = value.lower()
    req = req.lower()
    words = req.split()

    op = method = None
    if words:
        op = words.pop(0)
        method = _op_methods.get(op)

    if op != '<or>' and not method:
        if type(value) is bool:
            return value == strutils.bool_from_string(
                req, strict=False, default=req)
        else:
            return value == req

    if value is None:
        return False

    if op == '<or>':  # Ex: <or> v1 <or> v2 <or> v3
        while True:
            if words.pop(0) == value:
                return True
            if not words:
                break
            op = words.pop(0)  # remove a keyword <or>
            if not words:
                break
        return False

    try:
        if words and method(value, words[0]):
            return True
    except ValueError:
        pass

    return False 
Example #22
Source File: base.py    From watcher with Apache License 2.0 5 votes vote down vote up
def filter_instances_by_audit_tag(self, instances):
        if not self.config.check_optimize_metadata:
            return instances
        instances_to_migrate = []
        for instance in instances:
            optimize = True
            if instance.metadata:
                try:
                    optimize = strutils.bool_from_string(
                        instance.metadata.get('optimize'))
                except ValueError:
                    optimize = False
            if optimize:
                instances_to_migrate.append(instance)
        return instances_to_migrate 
Example #23
Source File: client_cmode.py    From manila with Apache License 2.0 5 votes vote down vote up
def delete_snapshot(self, volume_name, snapshot_name, ignore_owners=False):
        """Deletes a volume snapshot."""

        ignore_owners = ('true' if strutils.bool_from_string(ignore_owners)
                         else 'false')

        api_args = {
            'volume': volume_name,
            'snapshot': snapshot_name,
            'ignore-owners': ignore_owners,
        }
        self.send_request('snapshot-delete', api_args) 
Example #24
Source File: 38e632621e5a_change_volume_type_to_share_type.py    From manila with Apache License 2.0 5 votes vote down vote up
def _copy_records(destination_table, up_migration=True):
    old = ('volume', '')
    new = ('share', 'spec_')
    data_from, data_to = (old, new) if up_migration else (new, old)
    from_table = table(
        data_from[0] + '_type_extra_specs',
        sa.Column('created_at', sa.DateTime),
        sa.Column('updated_at', sa.DateTime),
        sa.Column('deleted_at', sa.DateTime),
        sa.Column('deleted', sa.Boolean if up_migration else sa.Integer),
        sa.Column('id', sa.Integer, primary_key=True, nullable=False),
        sa.Column(data_from[0] + '_type_id', sa.String(length=36)),
        sa.Column(data_from[1] + 'key', sa.String(length=255)),
        sa.Column(data_from[1] + 'value', sa.String(length=255)))

    extra_specs = []
    for es in op.get_bind().execute(from_table.select()):
        if up_migration:
            deleted = strutils.int_from_bool_as_string(es.deleted)
        else:
            deleted = strutils.bool_from_string(es.deleted, default=True)
        extra_specs.append({
            'created_at': es.created_at,
            'updated_at': es.updated_at,
            'deleted_at': es.deleted_at,
            'deleted': deleted,
            data_to[0] + '_type_id': getattr(es, data_from[0] + '_type_id'),
            data_to[1] + 'key': getattr(es, data_from[1] + 'key'),
            data_to[1] + 'value': getattr(es, data_from[1] + 'value'),
        })
    op.bulk_insert(destination_table, extra_specs) 
Example #25
Source File: common.py    From manila with Apache License 2.0 5 votes vote down vote up
def validate_public_share_policy(context, api_params, api='create'):
    """Validates if policy allows is_public parameter to be set to True.

    :arg api_params - A dictionary of values that may contain 'is_public'
    :returns api_params with 'is_public' item sanitized if present
    :raises exception.InvalidParameterValue if is_public is set but is Invalid
            exception.NotAuthorized if is_public is True but policy prevents it
    """
    if 'is_public' not in api_params:
        return api_params

    policies = {
        'create': 'create_public_share',
        'update': 'set_public_share',
    }
    policy_to_check = policies[api]
    try:
        api_params['is_public'] = strutils.bool_from_string(
            api_params['is_public'], strict=True)
    except ValueError as e:
        raise exception.InvalidParameterValue(six.text_type(e))

    public_shares_allowed = policy.check_policy(
        context, 'share', policy_to_check, do_raise=False)
    if api_params['is_public'] and not public_shares_allowed:
        message = _("User is not authorized to set 'is_public' to True in the "
                    "request.")
        raise exception.NotAuthorized(message=message)

    return api_params 
Example #26
Source File: wsgi.py    From manila with Apache License 2.0 5 votes vote down vote up
def set_api_version_request(self):
        """Set API version request based on the request header information.

        Microversions starts with /v2, so if a client sends a /v1 URL, then
        ignore the headers and request 1.0 APIs.
        """
        if not self.script_name or not (V1_SCRIPT_NAME in self.script_name or
                                        V2_SCRIPT_NAME in self.script_name):
            # The request is on the base URL without a major version specified
            self.api_version_request = api_version.APIVersionRequest()
        elif V1_SCRIPT_NAME in self.script_name:
            self.api_version_request = api_version.APIVersionRequest('1.0')
        else:
            if API_VERSION_REQUEST_HEADER in self.headers:
                hdr_string = self.headers[API_VERSION_REQUEST_HEADER]
                self.api_version_request = api_version.APIVersionRequest(
                    hdr_string)

                # Check that the version requested is within the global
                # minimum/maximum of supported API versions
                if not self.api_version_request.matches(
                        api_version.min_api_version(),
                        api_version.max_api_version()):
                    raise exception.InvalidGlobalAPIVersion(
                        req_ver=self.api_version_request.get_string(),
                        min_ver=api_version.min_api_version().get_string(),
                        max_ver=api_version.max_api_version().get_string())

            else:
                self.api_version_request = api_version.APIVersionRequest(
                    api_version.DEFAULT_API_VERSION)

        # Check if experimental API was requested
        if EXPERIMENTAL_API_REQUEST_HEADER in self.headers:
            self.api_version_request.experimental = strutils.bool_from_string(
                self.headers[EXPERIMENTAL_API_REQUEST_HEADER]) 
Example #27
Source File: export_locations.py    From manila with Apache License 2.0 5 votes vote down vote up
def add_preferred_path_attribute(self, context, view_dict,
                                     export_location):
        view_dict['preferred'] = strutils.bool_from_string(
            export_location['el_metadata'].get('preferred')) 
Example #28
Source File: share_types.py    From manila with Apache License 2.0 5 votes vote down vote up
def is_valid_required_extra_spec(key, value):
    """Validates required extra_spec value.

    :param key: extra_spec name
    :param value: extra_spec value
    :return: None if provided extra_spec is not required
             True/False if extra_spec is required and valid or not.
    """
    if key not in get_required_extra_specs():
        return

    if key == constants.ExtraSpecs.DRIVER_HANDLES_SHARE_SERVERS:
        return strutils.bool_from_string(value, default=None) is not None

    return False 
Example #29
Source File: client_cmode.py    From manila with Apache License 2.0 5 votes vote down vote up
def get_aggregate(self, aggregate_name):
        """Get aggregate attributes needed for the storage service catalog."""

        if not aggregate_name:
            return {}

        desired_attributes = {
            'aggr-attributes': {
                'aggregate-name': None,
                'aggr-raid-attributes': {
                    'raid-type': None,
                    'is-hybrid': None,
                },
            },
        }

        try:
            aggrs = self._get_aggregates(aggregate_names=[aggregate_name],
                                         desired_attributes=desired_attributes)
        except netapp_api.NaApiError:
            msg = _('Failed to get info for aggregate %s.')
            LOG.exception(msg, aggregate_name)
            return {}

        if len(aggrs) < 1:
            return {}

        aggr_attributes = aggrs[0]
        aggr_raid_attrs = aggr_attributes.get_child_by_name(
            'aggr-raid-attributes') or netapp_api.NaElement('none')

        aggregate = {
            'name': aggr_attributes.get_child_content('aggregate-name'),
            'raid-type': aggr_raid_attrs.get_child_content('raid-type'),
            'is-hybrid': strutils.bool_from_string(
                aggr_raid_attrs.get_child_content('is-hybrid')),
        }

        return aggregate 
Example #30
Source File: smartx.py    From manila with Apache License 2.0 5 votes vote down vote up
def get_smartcache_opts(self, opts):
        if strutils.bool_from_string(opts['huawei_smartcache']):
            if not opts['cachename']:
                raise exception.InvalidInput(
                    reason=_('Cache name is None, please set '
                             'huawei_smartcache:cachename in key.'))
        else:
            opts['cachename'] = None

        return opts