当前位置: 首页>>代码示例>>Python>>正文


Python _i18n._函数代码示例

本文整理汇总了Python中neutron._i18n._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _validate

    def _validate(self, context, subport):
        # Check that the subport doesn't reference the same port_id as a
        # trunk we may be in the middle of trying to create, in other words
        # make the validation idiot proof.
        if subport['port_id'] == self.trunk_port_id:
            raise trunk_exc.ParentPortInUse(port_id=subport['port_id'])

        # If the segmentation details are missing, we will need to
        # figure out defaults when the time comes to support Ironic.
        # We can reasonably expect segmentation details to be provided
        # in all other cases for now.
        segmentation_id = subport.get("segmentation_id")
        segmentation_type = subport.get("segmentation_type")
        if not segmentation_id or not segmentation_type:
            msg = _("Invalid subport details '%s': missing segmentation "
                    "information. Must specify both segmentation_id and "
                    "segmentation_type") % subport
            raise n_exc.InvalidInput(error_message=msg)

        if segmentation_type not in self._segmentation_types:
            msg = _("Invalid segmentation_type '%s'") % segmentation_type
            raise n_exc.InvalidInput(error_message=msg)

        if not self._segmentation_types[segmentation_type](segmentation_id):
            msg = _("Invalid segmentation id '%s'") % segmentation_id
            raise n_exc.InvalidInput(error_message=msg)

        trunk_validator = TrunkPortValidator(subport['port_id'])
        trunk_validator.validate(context)
        return subport
开发者ID:biruce-openstack,项目名称:neutron,代码行数:30,代码来源:rules.py

示例2: _validate_fixed_ips

def _validate_fixed_ips(data, valid_values=None):
    if not isinstance(data, list):
        msg = _("Invalid data format for fixed IP: '%s'") % data
        LOG.debug(msg)
        return msg

    ips = []
    for fixed_ip in data:
        if not isinstance(fixed_ip, dict):
            msg = _("Invalid data format for fixed IP: '%s'") % fixed_ip
            LOG.debug(msg)
            return msg
        if 'ip_address' in fixed_ip:
            # Ensure that duplicate entries are not set - just checking IP
            # suffices. Duplicate subnet_id's are legitimate.
            fixed_ip_address = fixed_ip['ip_address']
            if fixed_ip_address in ips:
                msg = _("Duplicate IP address '%s'") % fixed_ip_address
                LOG.debug(msg)
            else:
                msg = _validate_ip_address(fixed_ip_address)
            if msg:
                return msg
            ips.append(fixed_ip_address)
        if 'subnet_id' in fixed_ip:
            msg = _validate_uuid(fixed_ip['subnet_id'])
            if msg:
                return msg
开发者ID:simudream,项目名称:neutron,代码行数:28,代码来源:attributes.py

示例3: _verify_dict_keys

def _verify_dict_keys(expected_keys, target_dict, strict=True):
    """Allows to verify keys in a dictionary.

    :param expected_keys: A list of keys expected to be present.
    :param target_dict: The dictionary which should be verified.
    :param strict: Specifies whether additional keys are allowed to be present.
    :return: True, if keys in the dictionary correspond to the specification.
    """
    if not isinstance(target_dict, dict):
        msg = (_("Invalid input. '%(target_dict)s' must be a dictionary "
                 "with keys: %(expected_keys)s") %
               {'target_dict': target_dict, 'expected_keys': expected_keys})
        LOG.debug(msg)
        return msg

    expected_keys = set(expected_keys)
    provided_keys = set(target_dict.keys())

    predicate = expected_keys.__eq__ if strict else expected_keys.issubset

    if not predicate(provided_keys):
        msg = (_("Validation of dictionary's keys failed. "
                 "Expected keys: %(expected_keys)s "
                 "Provided keys: %(provided_keys)s") %
               {'expected_keys': expected_keys,
                'provided_keys': provided_keys})
        LOG.debug(msg)
        return msg
开发者ID:simudream,项目名称:neutron,代码行数:28,代码来源:attributes.py

示例4: _send_msg

 def _send_msg(self, msg, reply_cls=None, reply_multi=False,
               active_bundle=None):
     timeout_sec = cfg.CONF.OVS.of_request_timeout
     timeout = eventlet.Timeout(seconds=timeout_sec)
     if active_bundle is not None:
         (dp, ofp, ofpp) = self._get_dp()
         msg = ofpp.ONFBundleAddMsg(dp, active_bundle['id'],
                                    active_bundle['bundle_flags'], msg, [])
     try:
         result = ofctl_api.send_msg(self._app, msg, reply_cls, reply_multi)
     except ryu_exc.RyuException as e:
         m = _("ofctl request %(request)s error %(error)s") % {
             "request": msg,
             "error": e,
         }
         LOG.error(m)
         # NOTE(yamamoto): use RuntimeError for compat with ovs_lib
         raise RuntimeError(m)
     except eventlet.Timeout as e:
         with excutils.save_and_reraise_exception() as ctx:
             if e is timeout:
                 ctx.reraise = False
                 m = _("ofctl request %(request)s timed out") % {
                     "request": msg,
                 }
                 LOG.error(m)
                 # NOTE(yamamoto): use RuntimeError for compat with ovs_lib
                 raise RuntimeError(m)
     finally:
         timeout.cancel()
     LOG.debug("ofctl request %(request)s result %(result)s",
               {"request": msg, "result": result})
     return result
开发者ID:cubeek,项目名称:neutron,代码行数:33,代码来源:ofswitch.py

示例5: _validate_ip_address

def _validate_ip_address(data, valid_values=None):
    msg = None
    try:
        # netaddr.core.ZEROFILL is only applicable to IPv4.
        # it will remove leading zeros from IPv4 address octets.
        ip = netaddr.IPAddress(_validate_no_whitespace(data),
                               flags=netaddr.core.ZEROFILL)
        # The followings are quick checks for IPv6 (has ':') and
        # IPv4.  (has 3 periods like 'xx.xx.xx.xx')
        # NOTE(yamamoto): netaddr uses libraries provided by the underlying
        # platform to convert addresses.  For example, inet_aton(3).
        # Some platforms, including NetBSD and OS X, have inet_aton
        # implementation which accepts more varying forms of addresses than
        # we want to accept here.  The following check is to reject such
        # addresses.  For Example:
        #   >>> netaddr.IPAddress('1' * 59)
        #   IPAddress('199.28.113.199')
        #   >>> netaddr.IPAddress(str(int('1' * 59) & 0xffffffff))
        #   IPAddress('199.28.113.199')
        #   >>>
        if ':' not in data and data.count('.') != 3:
            msg = _("'%s' is not a valid IP address") % data
        # A leading '0' in IPv4 address may be interpreted as an octal number,
        # e.g. 011 octal is 9 decimal. Since there is no standard saying
        # whether IP address with leading '0's should be interpreted as octal
        # or decimal, hence we reject leading '0's to avoid ambiguity.
        if ip.version == 4 and str(ip) != data:
            msg = _("'%(data)s' is not an accepted IP address, "
                    "'%(ip)s' is recommended") % {"data": data, "ip": ip}
    except Exception:
        msg = _("'%s' is not a valid IP address") % data
    if msg:
        LOG.debug(msg)
    return msg
开发者ID:simudream,项目名称:neutron,代码行数:34,代码来源:attributes.py

示例6: parse_exclude_devices

def parse_exclude_devices(exclude_list):
    """Parse Exclude devices list

    parses excluded device list in the form:
    dev_name:pci_dev_1;pci_dev_2
    @param exclude list: list of string pairs in "key:value" format
                        the key part represents the network device name
                        the value part is a list of PCI slots separated by ";"
    """
    exclude_mapping = {}
    for dev_mapping in exclude_list:
        try:
            dev_name, exclude_devices = dev_mapping.split(":", 1)
        except ValueError:
            raise ValueError(_("Invalid mapping: '%s'") % dev_mapping)
        dev_name = dev_name.strip()
        if not dev_name:
            raise ValueError(_("Missing key in mapping: '%s'") % dev_mapping)
        if dev_name in exclude_mapping:
            raise ValueError(_("Device %(dev_name)s in mapping: %(mapping)s "
                               "not unique") % {'dev_name': dev_name,
                                                'mapping': dev_mapping})
        exclude_devices_list = exclude_devices.split(";")
        exclude_devices_set = set()
        for dev in exclude_devices_list:
            dev = dev.strip()
            if dev:
                exclude_devices_set.add(dev)
        exclude_mapping[dev_name] = exclude_devices_set
    return exclude_mapping
开发者ID:cloudbase,项目名称:neutron,代码行数:30,代码来源:config.py

示例7: _build_flow_expr_str

def _build_flow_expr_str(flow_dict, cmd):
    flow_expr_arr = []
    actions = None

    if cmd == 'add':
        flow_expr_arr.append("hard_timeout=%s" %
                             flow_dict.pop('hard_timeout', '0'))
        flow_expr_arr.append("idle_timeout=%s" %
                             flow_dict.pop('idle_timeout', '0'))
        flow_expr_arr.append("priority=%s" %
                             flow_dict.pop('priority', '1'))
    elif 'priority' in flow_dict:
        msg = _("Cannot match priority on flow deletion or modification")
        raise exceptions.InvalidInput(error_message=msg)

    if cmd != 'del':
        if "actions" not in flow_dict:
            msg = _("Must specify one or more actions on flow addition"
                    " or modification")
            raise exceptions.InvalidInput(error_message=msg)
        actions = "actions=%s" % flow_dict.pop('actions')

    for key, value in six.iteritems(flow_dict):
        if key == 'proto':
            flow_expr_arr.append(value)
        else:
            flow_expr_arr.append("%s=%s" % (key, str(value)))

    if actions:
        flow_expr_arr.append(actions)

    return ','.join(flow_expr_arr)
开发者ID:2020human,项目名称:neutron,代码行数:32,代码来源:ovs_lib.py

示例8: scan_vf_devices

    def scan_vf_devices(cls, dev_name):
        """Scan os directories to get VF devices

        @param dev_name: pf network device name
        @return: list of virtual functions
        """
        vf_list = []
        dev_path = cls.DEVICE_PATH % dev_name
        if not os.path.isdir(dev_path):
            LOG.error(_LE("Failed to get devices for %s"), dev_name)
            raise exc.InvalidDeviceError(dev_name=dev_name,
                                         reason=_("Device not found"))
        file_list = os.listdir(dev_path)
        for file_name in file_list:
            pattern_match = cls.VIRTFN_REG_EX.match(file_name)
            if pattern_match:
                vf_index = int(pattern_match.group("vf_index"))
                file_path = os.path.join(dev_path, file_name)
                if os.path.islink(file_path):
                    file_link = os.readlink(file_path)
                    pci_slot = os.path.basename(file_link)
                    vf_list.append((pci_slot, vf_index))
        if not vf_list:
            raise exc.InvalidDeviceError(
                dev_name=dev_name,
                reason=_("Device has no virtual functions"))
        return vf_list
开发者ID:abhilabh,项目名称:neutron,代码行数:27,代码来源:eswitch_manager.py

示例9: parse_mappings

def parse_mappings(mapping_list, unique_values=True):
    """Parse a list of mapping strings into a dictionary.

    :param mapping_list: a list of strings of the form '<key>:<value>'
    :param unique_values: values must be unique if True
    :returns: a dict mapping keys to values
    """
    mappings = {}
    for mapping in mapping_list:
        mapping = mapping.strip()
        if not mapping:
            continue
        split_result = mapping.split(':')
        if len(split_result) != 2:
            raise ValueError(_("Invalid mapping: '%s'") % mapping)
        key = split_result[0].strip()
        if not key:
            raise ValueError(_("Missing key in mapping: '%s'") % mapping)
        value = split_result[1].strip()
        if not value:
            raise ValueError(_("Missing value in mapping: '%s'") % mapping)
        if key in mappings:
            raise ValueError(_("Key %(key)s in mapping: '%(mapping)s' not "
                               "unique") % {'key': key, 'mapping': mapping})
        if unique_values and value in mappings.values():
            raise ValueError(_("Value %(value)s in mapping: '%(mapping)s' "
                               "not unique") % {'value': value,
                                                'mapping': mapping})
        mappings[key] = value
    return mappings
开发者ID:dlundquist,项目名称:neutron,代码行数:30,代码来源:utils.py

示例10: __init__

    def __init__(self, conf):
        LOG.debug("Initializing firewall agent")
        self.conf = conf
        fwaas_driver_class_path = provconf.get_provider_driver_class(
            cfg.CONF.fwaas.driver)
        self.fwaas_enabled = cfg.CONF.fwaas.enabled

        # None means l3-agent has no information on the server
        # configuration due to the lack of RPC support.
        if self.neutron_service_plugins is not None:
            fwaas_plugin_configured = (constants.FIREWALL
                                       in self.neutron_service_plugins)
            if fwaas_plugin_configured and not self.fwaas_enabled:
                msg = _("FWaaS plugin is configured in the server side, but "
                        "FWaaS is disabled in L3-agent.")
                LOG.error(msg)
                raise SystemExit(1)
            self.fwaas_enabled = self.fwaas_enabled and fwaas_plugin_configured

        if self.fwaas_enabled:
            try:
                self.fwaas_driver = importutils.import_object(
                    fwaas_driver_class_path)
                LOG.debug("FWaaS Driver Loaded: '%s'", fwaas_driver_class_path)
            except ImportError:
                msg = _('Error importing FWaaS device driver: %s')
                raise ImportError(msg % fwaas_driver_class_path)
        self.services_sync = False
        # setup RPC to msg fwaas plugin
        self.fwplugin_rpc = FWaaSL3PluginApi(topics.FIREWALL_PLUGIN,
                                             conf.host)
        super(FWaaSL3AgentRpcCallback, self).__init__(host=conf.host)
开发者ID:apporc,项目名称:neutron,代码行数:32,代码来源:firewall_l3_agent.py

示例11: _proxy_request

    def _proxy_request(self, instance_id, tenant_id, req):
        headers = {
            'X-Forwarded-For': req.headers.get('X-Forwarded-For'),
            'X-Instance-ID': instance_id,
            'X-Tenant-ID': tenant_id,
            'X-Instance-ID-Signature': self._sign_instance_id(instance_id)
        }

        nova_host_port = '%s:%s' % (self.conf.nova_metadata_host,
                                    self.conf.nova_metadata_port)
        url = urlparse.urlunsplit((
            self.conf.nova_metadata_protocol,
            nova_host_port,
            req.path_info,
            req.query_string,
            ''))

        disable_ssl_certificate_validation = self.conf.nova_metadata_insecure
        if self.conf.auth_ca_cert and not disable_ssl_certificate_validation:
            verify_cert = self.conf.auth_ca_cert
        else:
            verify_cert = not disable_ssl_certificate_validation

        client_cert = None
        if self.conf.nova_client_cert and self.conf.nova_client_priv_key:
            client_cert = (self.conf.nova_client_cert,
                           self.conf.nova_client_priv_key)

        resp = requests.request(method=req.method, url=url,
                                headers=headers,
                                data=req.body,
                                cert=client_cert,
                                verify=verify_cert)

        if resp.status_code == 200:
            req.response.content_type = resp.headers['content-type']
            req.response.body = resp.content
            LOG.debug(str(resp))
            return req.response
        elif resp.status_code == 403:
            LOG.warning(
                'The remote metadata server responded with Forbidden. This '
                'response usually occurs when shared secrets do not match.'
            )
            return webob.exc.HTTPForbidden()
        elif resp.status_code == 400:
            return webob.exc.HTTPBadRequest()
        elif resp.status_code == 404:
            return webob.exc.HTTPNotFound()
        elif resp.status_code == 409:
            return webob.exc.HTTPConflict()
        elif resp.status_code == 500:
            msg = _(
                'Remote metadata server experienced an internal server error.'
            )
            LOG.warning(msg)
            explanation = six.text_type(msg)
            return webob.exc.HTTPInternalServerError(explanation=explanation)
        else:
            raise Exception(_('Unexpected response code: %s') % resp.status)
开发者ID:cubeek,项目名称:neutron,代码行数:60,代码来源:agent.py

示例12: external_network_bridge_check

    def external_network_bridge_check(checker):
        if not cfg.CONF.database.connection:
            return upgradecheck.Result(
                upgradecheck.Code.WARNING,
                _("Database connection string is not set. Check of usage of "
                  "'external_network_bridge' config option in L3 agents "
                  "can't be done"))

        agents_with_external_bridge = []
        for agent in get_l3_agents():
            config_string = agent.get('configurations')
            if not config_string:
                continue
            config = jsonutils.loads(config_string)
            if config.get("external_network_bridge"):
                agents_with_external_bridge.append(agent.get("host"))

        if agents_with_external_bridge:
            return upgradecheck.Result(
                upgradecheck.Code.WARNING,
                _("L3 agents on hosts %s are still using "
                  "'external_network_bridge' config option to provide "
                  "gateway connectivity. This option is now removed. "
                  "Migration of routers from those L3 agents will be "
                  "required to connect them to external network through "
                  "integration bridge.") % agents_with_external_bridge)
        else:
            return upgradecheck.Result(
                upgradecheck.Code.SUCCESS,
                _("L3 agents are using integration bridge to connect external "
                  "gateways"))
开发者ID:openstack,项目名称:neutron,代码行数:31,代码来源:checks.py

示例13: blacklist_supported_vnic_types

    def blacklist_supported_vnic_types(self, vnic_types, blacklist):
        """Validate the blacklist and blacklist the supported_vnic_types

        :param vnic_types: The supported_vnic_types list
        :param blacklist: The blacklist as in vnic_type_blacklist
        :return The blacklisted vnic_types
        """
        if not blacklist:
            return vnic_types

        # Not valid values in the blacklist:
        if not all(bl in vnic_types for bl in blacklist):
            raise ValueError(_("Not all of the items from vnic_type_blacklist "
                               "are valid vnic_types for %(agent)s mechanism "
                               "driver. The valid values are: "
                               "%(valid_vnics)s.") %
                             {'agent': self.agent_type,
                              'valid_vnics': vnic_types})

        supported_vnic_types = [vnic_t for vnic_t in vnic_types if
                                vnic_t not in blacklist]

        # Nothing left in the supported vnict types list:
        if len(supported_vnic_types) < 1:
            raise ValueError(_("All possible vnic_types were blacklisted for "
                               "%s mechanism driver!") % self.agent_type)
        return supported_vnic_types
开发者ID:openstack,项目名称:neutron,代码行数:27,代码来源:mech_agent.py

示例14: main

def main():

    class SimpleDaemon(daemon.Daemon):
        """The purpose of this daemon is to serve as an example, and also as
        a dummy daemon, which can be invoked by functional testing, it
        does nothing but setting the pid file, and staying detached in the
        background.
        """

        def run(self):
            while True:
                time.sleep(10)

    opts = [
        cfg.StrOpt('uuid',
                   help=_('uuid provided from the command line '
                          'so external_process can track us via /proc/'
                          'cmdline interface.'),
                   required=True),
        cfg.StrOpt('pid_file',
                   help=_('Location of pid file of this process.'),
                   required=True)
    ]

    cfg.CONF.register_cli_opts(opts)
    # Don't get the default configuration file
    cfg.CONF(project='neutron', default_config_files=[])
    simple_daemon = SimpleDaemon(cfg.CONF.pid_file,
                                 uuid=cfg.CONF.uuid)
    simple_daemon.start()
开发者ID:21atlas,项目名称:neutron,代码行数:30,代码来源:simple_daemon.py

示例15: _validate_dns_name_with_dns_domain

def _validate_dns_name_with_dns_domain(request_dns_name):
    # If a PQDN was passed, make sure the FQDN that will be generated is of
    # legal size
    dns_domain = _get_dns_domain()
    higher_labels = dns_domain
    if dns_domain:
        higher_labels = '.%s' % dns_domain
    higher_labels_len = len(higher_labels)
    dns_name_len = len(request_dns_name)
    if not request_dns_name.endswith('.'):
        if dns_name_len + higher_labels_len > FQDN_MAX_LEN:
            msg = _("The dns_name passed is a PQDN and its size is "
                    "'%(dns_name_len)s'. The dns_domain option in "
                    "neutron.conf is set to %(dns_domain)s, with a "
                    "length of '%(higher_labels_len)s'. When the two are "
                    "concatenated to form a FQDN (with a '.' at the end), "
                    "the resulting length exceeds the maximum size "
                    "of '%(fqdn_max_len)s'"
                    ) % {'dns_name_len': dns_name_len,
                         'dns_domain': cfg.CONF.dns_domain,
                         'higher_labels_len': higher_labels_len,
                         'fqdn_max_len': FQDN_MAX_LEN}
            return msg
        return

    # A FQDN was passed
    if (dns_name_len <= higher_labels_len or not
        request_dns_name.endswith(higher_labels)):
        msg = _("The dns_name passed is a FQDN. Its higher level labels "
                "must be equal to the dns_domain option in neutron.conf, "
                "that has been set to '%(dns_domain)s'. It must also "
                "include one or more valid DNS labels to the left "
                "of '%(dns_domain)s'") % {'dns_domain':
                                          cfg.CONF.dns_domain}
        return msg
开发者ID:abhilabh,项目名称:neutron,代码行数:35,代码来源:dns.py


注:本文中的neutron._i18n._函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。