Python oslo_utils.importutils.import_class() Examples

The following are 30 code examples of oslo_utils.importutils.import_class(). 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.importutils , or try the search function .
Example #1
Source File: utils.py    From python-tackerclient with Apache License 2.0 6 votes vote down vote up
def get_client_class(api_name, version, version_map):
    """Returns the client class for the requested API version.

    :param api_name: the name of the API, e.g. 'compute', 'image', etc
    :param version: the requested API version
    :param version_map: a dict of client classes keyed by version
    :rtype: a client class for the requested API version
    """
    try:
        client_path = version_map[str(version)]
    except (KeyError, ValueError):
        msg = _("Invalid %(api_name)s client version '%(version)s'. must be "
                "one of: %(map_keys)s")
        msg = msg % {'api_name': api_name, 'version': version,
                     'map_keys': ', '.join(version_map.keys())}
        raise exceptions.UnsupportedVersion(message=msg)

    return importutils.import_class(client_path) 
Example #2
Source File: utils.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_client_class(api_name, version, version_map):
    """Returns the client class for the requested API version.

    :param api_name: the name of the API, e.g. 'compute', 'image', etc
    :param version: the requested API version
    :param version_map: a dict of client classes keyed by version
    :rtype: a client class for the requested API version
    """
    try:
        client_path = version_map[str(version)]
    except (KeyError, ValueError):
        msg = _("Invalid %(api_name)s client version '%(version)s'. must be "
                "one of: %(map_keys)s")
        msg = msg % {'api_name': api_name, 'version': version,
                     'map_keys': ', '.join(version_map.keys())}
        raise exceptions.UnsupportedVersion(msg)

    return importutils.import_class(client_path) 
Example #3
Source File: service.py    From ec2-api with Apache License 2.0 6 votes vote down vote up
def _get_manager(self):
        """Initialize a Manager object appropriate for this service.

        Use the service name to look up a Manager subclass from the
        configuration and initialize an instance. If no class name
        is configured, just return None.

        :returns: a Manager instance, or None.

        """
        fl = '%s_manager' % self.name
        if fl not in CONF:
            return None

        manager_class_name = CONF.get(fl, None)
        if not manager_class_name:
            return None

        manager_class = importutils.import_class(manager_class_name)
        return manager_class() 
Example #4
Source File: __init__.py    From castellan with Apache License 2.0 6 votes vote down vote up
def API(configuration=None):
    conf = configuration or cfg.CONF
    conf.register_opts(key_manager_opts, group='key_manager')

    try:
        mgr = driver.DriverManager("castellan.drivers",
                                   conf.key_manager.backend,
                                   invoke_on_load=True,
                                   invoke_args=[conf])
        key_mgr = mgr.driver
    except exception.NoMatches:
        LOG.warning("Deprecation Warning : %s is not a stevedore based driver,"
                    " trying to load it as a class", conf.key_manager.backend)
        cls = importutils.import_class(conf.key_manager.backend)
        key_mgr = cls(configuration=conf)

    return migration.handle_migration(conf, key_mgr) 
Example #5
Source File: client.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_class(api_name, version, version_map):
        """Returns the client class for the requested API version

        :param api_name: the name of the API, e.g. 'compute', 'image', etc
        :param version: the requested API version
        :param version_map: a dict of client classes keyed by version
        :rtype: a client class for the requested API version
        """
        try:
            client_path = version_map[str(version)]
        except (KeyError, ValueError):
            msg = _("Invalid %(api_name)s client version '%(version)s'. "
                    "Must be one of: %(version_map)s") % {
                        'api_name': api_name,
                        'version': version,
                        'version_map': ', '.join(version_map.keys())}
            raise exceptions.UnsupportedVersion(msg)

        return importutils.import_class(client_path) 
Example #6
Source File: loadables.py    From zun with Apache License 2.0 6 votes vote down vote up
def get_matching_classes(self, loadable_class_names):
        """Get loadable classes from a list of names.

        Each name can be a full module path or the full path to a
        method that returns classes to use.  The latter behavior
        is useful to specify a method that returns a list of
        classes to use in a default case.
        """

        classes = []
        for cls_name in loadable_class_names:
            obj = importutils.import_class(cls_name)
            if self._is_correct_class(obj):
                classes.append(obj)
            elif inspect.isfunction(obj):
                # Get list of classes from a function
                for cls in obj():
                    classes.append(cls)
            else:
                error_str = 'Not a class of the correct type'
                raise exception.ClassNotFound(class_name=cls_name,
                                              exception=error_str)
        return classes 
Example #7
Source File: client.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_class(api_name, version, version_map):
        """Returns the client class for the requested API version

        :param api_name: the name of the API, e.g. 'compute', 'image', etc
        :param version: the requested API version
        :param version_map: a dict of client classes keyed by version
        :rtype: a client class for the requested API version
        """
        try:
            client_path = version_map[str(version)]
        except (KeyError, ValueError):
            msg = _("Invalid %(api_name)s client version '%(version)s'. "
                    "Must be one of: %(version_map)s") % {
                        'api_name': api_name,
                        'version': version,
                        'version_map': ', '.join(version_map.keys())}
            raise exceptions.UnsupportedVersion(msg)

        return importutils.import_class(client_path) 
Example #8
Source File: client.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_class(api_name, version, version_map):
        """Returns the client class for the requested API version

        :param api_name: the name of the API, e.g. 'compute', 'image', etc
        :param version: the requested API version
        :param version_map: a dict of client classes keyed by version
        :rtype: a client class for the requested API version
        """
        try:
            client_path = version_map[str(version)]
        except (KeyError, ValueError):
            msg = _("Invalid %(api_name)s client version '%(version)s'. "
                    "Must be one of: %(version_map)s") % {
                        'api_name': api_name,
                        'version': version,
                        'version_map': ', '.join(version_map.keys())}
            raise exceptions.UnsupportedVersion(msg)

        return importutils.import_class(client_path) 
Example #9
Source File: client.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def get_class(api_name, version, version_map):
        """Returns the client class for the requested API version

        :param api_name: the name of the API, e.g. 'compute', 'image', etc
        :param version: the requested API version
        :param version_map: a dict of client classes keyed by version
        :rtype: a client class for the requested API version
        """
        try:
            client_path = version_map[str(version)]
        except (KeyError, ValueError):
            msg = _("Invalid %(api_name)s client version '%(version)s'. "
                    "Must be one of: %(version_map)s") % {
                        'api_name': api_name,
                        'version': version,
                        'version_map': ', '.join(version_map.keys())}
            raise exceptions.UnsupportedVersion(msg)

        return importutils.import_class(client_path) 
Example #10
Source File: service.py    From manila with Apache License 2.0 6 votes vote down vote up
def __init__(self, host, binary, topic, manager, report_interval=None,
                 periodic_interval=None, periodic_fuzzy_delay=None,
                 service_name=None, coordination=False, *args, **kwargs):
        super(Service, self).__init__()
        if not rpc.initialized():
            rpc.init(CONF)
        self.host = host
        self.binary = binary
        self.topic = topic
        self.manager_class_name = manager
        manager_class = importutils.import_class(self.manager_class_name)
        self.manager = manager_class(host=self.host,
                                     service_name=service_name,
                                     *args, **kwargs)
        self.availability_zone = self.manager.availability_zone
        self.report_interval = report_interval
        self.periodic_interval = periodic_interval
        self.periodic_fuzzy_delay = periodic_fuzzy_delay
        self.saved_args, self.saved_kwargs = args, kwargs
        self.timers = []
        self.coordinator = coordination 
Example #11
Source File: extensions.py    From masakari with Apache License 2.0 6 votes vote down vote up
def load_extension(self, ext_factory):
        """Execute an extension factory.

        Loads an extension.  The 'ext_factory' is the name of a
        callable that will be imported and called with one
        argument--the extension manager.  The factory callable is
        expected to call the register() method at least once.
        """

        LOG.debug("Loading extension %s", ext_factory)

        if isinstance(ext_factory, six.string_types):
            # Load the factory
            factory = importutils.import_class(ext_factory)
        else:
            factory = ext_factory

        # Call it
        LOG.debug("Calling extension factory %s", ext_factory)
        factory(self) 
Example #12
Source File: extensions.py    From manila with Apache License 2.0 6 votes vote down vote up
def load_extension(self, ext_factory):
        """Execute an extension factory.

        Loads an extension.  The 'ext_factory' is the name of a
        callable that will be imported and called with one
        argument--the extension manager.  The factory callable is
        expected to call the register() method at least once.
        """

        LOG.debug("Loading extension %s", ext_factory)

        # Load the factory
        factory = importutils.import_class(ext_factory)

        # Call it
        LOG.debug("Calling extension factory %s", ext_factory)
        factory(self) 
Example #13
Source File: service.py    From karbor with Apache License 2.0 6 votes vote down vote up
def _get_manager(self):
        """Initialize a Manager object appropriate for this service.

        Use the service name to look up a Manager subclass from the
        configuration and initialize an instance. If no class name
        is configured, just return None.

        :returns: a Manager instance, or None.

        """
        fl = '%s_manager' % self.name
        if fl not in CONF:
            return None

        manager_class_name = CONF.get(fl, None)
        if not manager_class_name:
            return None

        manager_class = importutils.import_class(manager_class_name)
        return manager_class() 
Example #14
Source File: service.py    From karbor with Apache License 2.0 6 votes vote down vote up
def __init__(self, host, binary, topic, manager, report_interval=None,
                 periodic_interval=None, periodic_fuzzy_delay=None,
                 service_name=None, *args, **kwargs):
        super(Service, self).__init__()

        rpc.init(CONF)

        self.host = host
        self.binary = binary
        self.topic = topic
        self.manager_class_name = manager
        manager_class = importutils.import_class(self.manager_class_name)
        self.manager = manager_class(host=self.host,
                                     service_name=service_name,
                                     *args, **kwargs)
        self.report_interval = report_interval
        self.periodic_interval = periodic_interval
        self.periodic_fuzzy_delay = periodic_fuzzy_delay
        self.basic_config_check()
        self.saved_args, self.saved_kwargs = args, kwargs
        self.timers = []

        self.rpcserver = None 
Example #15
Source File: test_file_system_bank_plugin.py    From karbor with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(FileSystemBankPluginTest, self).setUp()

        import_str = (
            "karbor.services.protection.bank_plugins."
            "file_system_bank_plugin.FileSystemBankPlugin"
        )
        plugin_config = cfg.ConfigOpts()
        plugin_config_fixture = self.useFixture(fixture.Config(plugin_config))
        plugin_config_fixture.load_raw_values(
            group='file_system_bank_plugin',
            file_system_bank_path=tempfile.mkdtemp(),
        )
        fs_bank_plugin_cls = importutils.import_class(
            import_str=import_str)
        self.fs_bank_plugin = fs_bank_plugin_cls(plugin_config) 
Example #16
Source File: loadables.py    From karbor with Apache License 2.0 6 votes vote down vote up
def get_matching_classes(self, loadable_class_names):
        """Get loadable classes from a list of names.

        Each name can be a full module path or the full path to a method that
        returns classes to use. The latter behavior is useful to specify a
        method that returns a list of classes to use in a default case.
        """

        classes = []
        for cls_name in loadable_class_names:
            obj = importutils.import_class(cls_name)
            if self._is_correct_class(obj):
                classes.append(obj)
            elif inspect.isfunction(obj):
                # Get list of classes from a function
                for cls in obj():
                    classes.append(cls)
            else:
                error_str = 'Not a class of the correct type'
                raise exception.ClassNotFound(class_name=cls_name,
                                              exception=error_str)
        return classes 
Example #17
Source File: generator_factory.py    From mistral-extra with Apache License 2.0 6 votes vote down vote up
def all_generators():
    for mod_name in SUPPORTED_MODULES:
        prefix = mod_name.replace(' ', '')
        mod_namespace = mod_name.lower().replace(' ', '_')
        mod_cls_name = 'mistral_extra.actions.openstack.actions.%sAction' \
                       % prefix
        mod_action_cls = importutils.import_class(mod_cls_name)
        generator_cls_name = '%sActionGenerator' % prefix

        yield type(
            generator_cls_name,
            (base.OpenStackActionGenerator,),
            {
                'action_namespace': mod_namespace,
                'base_action_class': mod_action_cls
            }
        ) 
Example #18
Source File: utils.py    From dragonflow with Apache License 2.0 6 votes vote down vote up
def load_driver(driver_cfg, namespace, *args, **kwargs):
    try:
        # Try to resolve by alias
        mgr = driver.DriverManager(namespace, driver_cfg)
        class_to_load = mgr.driver
    except RuntimeError:
        e1_info = sys.exc_info()
        # try with name
        try:
            class_to_load = importutils.import_class(driver_cfg)
        except (ImportError, ValueError):
            LOG.error("Error loading class %(class)s by alias e: %(e)s",
                      {'class': driver_cfg, 'e': e1_info},
                      exc_info=e1_info)
            LOG.error("Error loading class by class name",
                      exc_info=True)
            raise ImportError(_("Class not found."))
    return class_to_load(*args, **kwargs) 
Example #19
Source File: service.py    From masakari with Apache License 2.0 6 votes vote down vote up
def __init__(self, host, binary, topic, manager,
                 periodic_enable=None, periodic_fuzzy_delay=None,
                 periodic_interval_max=None):
        super(Service, self).__init__()

        if not rpc.initialized():
            rpc.init(CONF)

        self.host = host
        self.binary = binary
        self.topic = topic
        self.manager_class_name = manager
        manager_class = importutils.import_class(self.manager_class_name)
        self.rpcserver = None
        self.manager = manager_class(host=self.host)
        self.periodic_enable = periodic_enable
        self.periodic_fuzzy_delay = periodic_fuzzy_delay
        self.periodic_interval_max = periodic_interval_max 
Example #20
Source File: service.py    From manila with Apache License 2.0 6 votes vote down vote up
def _get_manager(self):
        """Initialize a Manager object appropriate for this service.

        Use the service name to look up a Manager subclass from the
        configuration and initialize an instance. If no class name
        is configured, just return None.

        :returns: a Manager instance, or None.

        """
        fl = '%s_manager' % self.name
        if fl not in CONF:
            return None

        manager_class_name = CONF.get(fl, None)
        if not manager_class_name:
            return None

        manager_class = importutils.import_class(manager_class_name)
        return manager_class() 
Example #21
Source File: test_datasource_update_method.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def test_datasource_update_method_push(self):
        driver_names = ds_utils.get_push_drivers_names()
        push_drivers = ds_utils.get_drivers_by_name(driver_names)
        self.assertSequenceEqual({utils.import_class(
            self.conf[NOVA_INSTANCE_DATASOURCE].driver), utils.import_class(
            self.conf[ZABBIX_DATASOURCE_PUSH].driver)},
            set(d.__class__ for d in push_drivers)) 
Example #22
Source File: helpers.py    From taskflow with Apache License 2.0 5 votes vote down vote up
def _fetch_factory(factory_name):
    try:
        return importutils.import_class(factory_name)
    except (ImportError, ValueError) as e:
        raise ImportError("Could not import factory %r: %s"
                          % (factory_name, e)) 
Example #23
Source File: service.py    From tacker with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, binary, topic, manager, report_interval=None,
                 periodic_interval=None, periodic_fuzzy_delay=None,
                 *args, **kwargs):

        self.binary = binary
        self.manager_class_name = manager
        manager_class = importutils.import_class(self.manager_class_name)
        self.manager = manager_class(host=host, *args, **kwargs)
        self.report_interval = report_interval
        self.periodic_interval = periodic_interval
        self.periodic_fuzzy_delay = periodic_fuzzy_delay
        self.saved_args, self.saved_kwargs = args, kwargs
        self.timers = []
        super(Service, self).__init__(host, topic, manager=self.manager) 
Example #24
Source File: utils.py    From tacker with Apache License 2.0 5 votes vote down vote up
def load_class_by_alias_or_classname(namespace, name):
    """Load class using stevedore alias or the class name.

    Load class using the stevedore driver manager
    :param namespace: namespace where the alias is defined
    :param name: alias or class name of the class to be loaded
    :returns: class if calls can be loaded
    :raises ImportError: if class cannot be loaded
    """
    if not name:
        LOG.error("Alias or class name is not set")
        raise ImportError(_("Class not found."))
    try:
        # Try to resolve class by alias
        mgr = driver.DriverManager(namespace, name)
        class_to_load = mgr.driver
    except RuntimeError:
        e1_info = sys.exc_info()
        # Fallback to class name
        try:
            class_to_load = importutils.import_class(name)
        except (ImportError, ValueError):
            LOG.error("Error loading class by alias",
                      exc_info=e1_info)
            LOG.error("Error loading class by class name",
                      exc_info=True)
            raise ImportError(_("Class not found."))
    return class_to_load 
Example #25
Source File: __init__.py    From tacker with Apache License 2.0 5 votes vote down vote up
def API(auth_url, configuration=None):
    conf = configuration or cfg.CONF
    conf.register_opts(key_manager_opts, group='key_manager')

    cls = importutils.import_class(conf.key_manager.api_class)
    return cls(auth_url) 
Example #26
Source File: writer.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def _load_output_backend(self):
        backend = i_utils.import_class(CONF.output.backend)
        self._output = backend 
Example #27
Source File: utils.py    From masakari with Apache License 2.0 5 votes vote down vote up
def monkey_patch():
    """If the CONF.monkey_patch set as True,
    this function patches a decorator
    for all functions in specified modules.
    You can set decorators for each modules
    using CONF.monkey_patch_modules.
    The format is "Module path:Decorator function".

    name - name of the function
    function - object of the function
    """
    # If CONF.monkey_patch is not True, this function do nothing.
    if not CONF.monkey_patch:
        return
    if six.PY2:
        is_method = inspect.ismethod
    else:
        def is_method(obj):
            # Unbound methods became regular functions on Python 3
            return inspect.ismethod(obj) or inspect.isfunction(obj)
    # Get list of modules and decorators
    for module_and_decorator in CONF.monkey_patch_modules:
        module, decorator_name = module_and_decorator.split(':')
        # import decorator function
        decorator = importutils.import_class(decorator_name)
        __import__(module)
        # Retrieve module information using pyclbr
        module_data = pyclbr.readmodule_ex(module)
        for key, value in module_data.items():
            # set the decorator for the class methods
            if isinstance(value, pyclbr.Class):
                clz = importutils.import_class("%s.%s" % (module, key))
                for method, func in inspect.getmembers(clz, is_method):
                    setattr(clz, method,
                            decorator("%s.%s.%s" % (module, key,
                                                    method), func))
            # set the decorator for the function
            if isinstance(value, pyclbr.Function):
                func = importutils.import_class("%s.%s" % (module, key))
                setattr(sys.modules[module], key,
                        decorator("%s.%s" % (module, key), func)) 
Example #28
Source File: volumeops.py    From compute-hyperv with Apache License 2.0 5 votes vote down vote up
def _vmops(self):
        # We have to avoid a circular dependency.
        if not self._vmops_prop:
            self._vmops_prop = importutils.import_class(
                'compute_hyperv.nova.vmops.VMOps')()
        return self._vmops_prop 
Example #29
Source File: __init__.py    From designate with Apache License 2.0 5 votes vote down vote up
def start(self):
        LOG.debug('IPABackend start')
        self.request = requests.Session()
        authclassname = cfg.CONF[self.name].ipa_auth_driver_class
        authclass = importutils.import_class(authclassname)
        self.request.auth = \
            authclass(cfg.CONF[self.name].ipa_client_keytab,
                      cfg.CONF[self.name].ipa_host)
        ipa_base_url = cfg.CONF[self.name].ipa_base_url
        if ipa_base_url.startswith("http"):  # full URL
            self.baseurl = ipa_base_url
        else:  # assume relative to https://host[:port]
            self.baseurl = "https://" + cfg.CONF[self.name].ipa_host
            ipa_port = cfg.CONF[self.name].ipa_port
            if ipa_port != IPA_DEFAULT_PORT:
                self.baseurl += ":" + str(ipa_port)
            self.baseurl += ipa_base_url
        ipa_json_url = cfg.CONF[self.name].ipa_json_url
        if ipa_json_url.startswith("http"):  # full URL
            self.jsonurl = ipa_json_url
        else:  # assume relative to https://host[:port]
            self.jsonurl = self.baseurl + ipa_json_url
        xtra_hdrs = {'Content-Type': 'application/json',
                     'Referer': self.baseurl}
        self.request.headers.update(xtra_hdrs)
        self.request.verify = cfg.CONF[self.name].ipa_ca_cert
        self.ntries = cfg.CONF[self.name].ipa_connect_retries
        self.force = cfg.CONF[self.name].ipa_force_ns_use 
Example #30
Source File: volumeops.py    From compute-hyperv with Apache License 2.0 5 votes vote down vote up
def _block_dev_man(self):
        if not self._block_dev_man_prop:
            self._block_dev_man_prop = importutils.import_class(
                'compute_hyperv.nova.block_device_manager.'
                'BlockDeviceInfoManager')()
        return self._block_dev_man_prop