Python oslo_utils.importutils.import_module() Examples

The following are 30 code examples of oslo_utils.importutils.import_module(). 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: __init__.py    From monasca-api with Apache License 2.0 6 votes vote down vote up
def load_conf_modules():
    """Loads all modules that contain configuration.

    Method iterates over modules of :py:module:`monasca_api.conf`
    and imports only those that contain following methods:

    - list_opts (required by oslo_config.genconfig)
    - register_opts (required by :py:currentmodule:)

    """
    for modname in _list_module_names():
        mod = importutils.import_module('monasca_api.conf.' + modname)
        required_funcs = ['register_opts', 'list_opts']
        for func in required_funcs:
            if hasattr(mod, func):
                yield mod 
Example #2
Source File: __init__.py    From kuryr with Apache License 2.0 6 votes vote down vote up
def port_unbind(endpoint_id, neutron_port, driver=None, **kwargs):
    """Unbinds the Neutron port from the network interface on the host.

    :param endpoint_id: the ID of the Docker container as string
    :param neutron_port: a port dictionary returned from python-neutronclient
    :param driver:       the binding driver name
    :param kwargs:       Additional driver-specific arguments
    :returns: the tuple of stdout and stderr returned by processutils.execute
              invoked with the executable script for unbinding
    :raises: processutils.ProcessExecutionError, pyroute2.NetlinkError,
             kuryr.common.exceptions.DriverNotEnabledException,
    """
    driver = importutils.import_module(
        driver or cfg.CONF.binding.default_driver)
    _verify_driver(driver)

    return driver.port_unbind(endpoint_id, neutron_port, **kwargs) 
Example #3
Source File: plugin_reference.py    From ovn-scale-test with Apache License 2.0 6 votes vote down vote up
def make_plugin_base_section(plugin_group):
    elements = []

    for item in plugin_group["items"]:
        name = item["name"].title() if "SLA" != item["name"] else item["name"]
        category_obj = category("%s %ss" % (plugin_group["group"].title(),
                                            name))
        elements.append(category_obj)

        module, cls = item["base"].split(":")
        plugin_base = getattr(importutils.import_module(module), cls)

        for p in plugin_base.get_all():
            category_obj.append(make_plugin_section(p, item["name"]))

    return elements 
Example #4
Source File: __init__.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def load_conf_modules():
    """Loads all modules that contain configuration

    Method iterates over modules of :py:module:`monasca_log_api.conf`
    and imports only those that contain following methods:

    - list_opts (required by oslo_config.genconfig)
    - register_opts (required by :py:currentmodule:)

    """
    for modname in _list_module_names():
        mod = importutils.import_module('monasca_log_api.conf.' + modname)
        required_funcs = ['register_opts', 'list_opts']
        for func in required_funcs:
            if hasattr(mod, func):
                yield mod 
Example #5
Source File: client_factory.py    From karbor with Apache License 2.0 5 votes vote down vote up
def get_client_module(cls, service):
        if not cls._factory:
            cls._factory = {}
            for client_module in cls._list_clients():
                try:
                    client_module = importutils.import_module(client_module)
                except ImportError:
                    LOG.error('No module named %s', client_module)
                else:
                    cls._factory[client_module.SERVICE] = client_module
        return cls._factory.get(service) 
Example #6
Source File: __init__.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def load_policy_modules():
    """Load all modules that contain policies.

    Method iterates over modules of :py:mod:`monasca_events_api.policies`
    and imports only those that contain following methods:

    - list_rules

    """
    for modname in _list_module_names():
        mod = importutils.import_module(_BASE_MOD_PATH + modname)
        if hasattr(mod, 'list_rules'):
            yield mod 
Example #7
Source File: __init__.py    From monasca-notification with Apache License 2.0 5 votes vote down vote up
def register_enabled_plugin_opts(conf=None):
    if conf is None:
        conf = CONF
    for enabled_plugin in conf.notification_types.enabled:
        ep_module = importutils.import_module(enabled_plugin.split(":")[0])
        ep_module.register_opts(conf) 
Example #8
Source File: __init__.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def load_policy_modules():
    """Load all modules that contain policies.

    Method iterates over modules of :py:mod:`monasca_events_api.policies`
    and imports only those that contain following methods:

    - list_rules

    """
    for modname in _list_module_names():
        mod = importutils.import_module(_BASE_MOD_PATH + modname)
        if hasattr(mod, 'list_rules'):
            yield mod 
Example #9
Source File: utils.py    From python-senlinclient with Apache License 2.0 5 votes vote down vote up
def import_versioned_module(version, submodule=None):
    module = 'senlinclient.v%s' % version
    if submodule:
        module = '.'.join((module, submodule))
        return importutils.import_module(module) 
Example #10
Source File: utils.py    From karbor with Apache License 2.0 5 votes vote down vote up
def get_auth_uri(v3=True):
    # Look for the keystone auth_uri in the configuration. First we
    # check the [clients_keystone] section, and if it is not set we
    # look in [keystone_authtoken]
    if cfg.CONF.clients_keystone.auth_uri:
        discover = ks_discover.Discover(
            auth_url=cfg.CONF.clients_keystone.auth_uri)
        return discover.url_for('3.0')
    else:
        # Import auth_token to have keystone_authtoken settings setup.
        importutils.import_module('keystonemiddleware.auth_token')
        auth_uri = cfg.CONF.keystone_authtoken.www_authenticate_uri
        return auth_uri.replace('v2.0', 'v3') if auth_uri and v3 else auth_uri 
Example #11
Source File: loadables.py    From karbor with Apache License 2.0 5 votes vote down vote up
def _get_classes_from_module(self, module_name):
        """Get the classes from a module that match the type we want."""
        classes = []
        module = importutils.import_module(module_name)
        for obj_name in dir(module):
            # Skip objects that are meant to be private.
            if obj_name.startswith('_'):
                continue
            itm = getattr(module, obj_name)
            if self._is_correct_class(itm):
                classes.append(itm)
        return classes 
Example #12
Source File: api.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def _load_backend(self):
        with self._lock:
            if not self._backend:
                # Import the untranslated name if we don't have a mapping
                backend_path = self._backend_mapping.get(self._backend_name,
                                                         self._backend_name)
                LOG.debug('Loading backend %(name)r from %(path)r',
                          {'name': self._backend_name,
                           'path': backend_path})
                backend_mod = importutils.import_module(backend_path)
                self._backend = backend_mod.get_backend() 
Example #13
Source File: base.py    From karbor with Apache License 2.0 5 votes vote down vote up
def __init__(self, db_driver=None):
        # NOTE(mriedem): Without this call, multiple inheritance involving
        # the db Base class does not work correctly.
        super(Base, self).__init__()
        if not db_driver:
            db_driver = CONF.db_driver
        self.db = importutils.import_module(db_driver)  # pylint: disable=C0103
        self.db.dispose_engine() 
Example #14
Source File: __init__.py    From kuryr with Apache License 2.0 5 votes vote down vote up
def test__verify_driver(self):
        cfg.CONF.set_override('enabled_drivers',
                              ['kuryr.lib.binding.drivers.veth'],
                              group='binding')
        driver = importutils.import_module('kuryr.lib.binding.drivers.veth')
        binding._verify_driver(driver)  # assert no exception raise
        driver = importutils.import_module('kuryr.lib.binding.drivers.vlan')
        self.assertRaises(exceptions.DriverNotEnabledException,
                          binding._verify_driver, driver) 
Example #15
Source File: __init__.py    From kuryr with Apache License 2.0 5 votes vote down vote up
def _get_driver():
    global _driver
    if not _driver:
        driver_name = cfg.CONF.binding.default_driver.rsplit('.', 1)[1]

        # REVISIT(vikasc): Need to remove this if check
        if driver_name == 'vlan':
            seg_driver_path = '.'.join([BASE_PATH, driver_name])
            segmentation_driver = importutils.import_module(seg_driver_path)
            _driver = segmentation_driver.SegmentationDriver()
    return _driver 
Example #16
Source File: __init__.py    From kuryr with Apache License 2.0 5 votes vote down vote up
def port_bind(endpoint_id, port, subnets, network=None, vm_port=None,
              segmentation_id=None, driver=None, **kwargs):
    """Binds the Neutron port to the network interface on the host.

    :param endpoint_id:   the ID of the endpoint as string
    :param port:         the container Neutron port dictionary as returned by
                         python-neutronclient
    :param subnets:      an iterable of all the Neutron subnets which the
                         endpoint is trying to join
    :param network:      the Neutron network which the endpoint is trying to
                         join
    :param vm_port:      the Nova instance port dictionary, as returned by
                         python-neutronclient. Binding is being done for the
                         port of a container which is running inside this Nova
                         instance (either ipvlan/macvlan or a subport).
    :param segmentation_id: ID of the segment for container traffic isolation)
    :param driver:       the binding driver name
    :param kwargs:       Additional driver-specific arguments
    :returns: the tuple of the names of the veth pair and the tuple of stdout
              and stderr returned by processutils.execute invoked with the
              executable script for binding
    :raises: kuryr.common.exceptions.VethCreationFailure,
             kuryr.common.exceptions.DriverNotEnabledException,
             processutils.ProcessExecutionError
    """
    driver = importutils.import_module(
        driver or cfg.CONF.binding.default_driver)
    _verify_driver(driver)

    return driver.port_bind(endpoint_id, port, subnets, network=network,
                            vm_port=vm_port,
                            segmentation_id=segmentation_id,
                            **kwargs) 
Example #17
Source File: test_importutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def test_import_module(self):
        dt = importutils.import_module('datetime')
        self.assertEqual(sys.modules['datetime'], dt) 
Example #18
Source File: runtime.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def list_package_modules(package_name):
    """Get a list of the modules for a given package.

    :param package_name: The package name to get modules for.
    :returns: A list of module objects for the said package name.
    """
    pkg_mod = importutils.import_module(package_name)
    modules = [pkg_mod]

    for mod in pkgutil.walk_packages(pkg_mod.__path__):
        _, mod_name, _ = mod
        fq_name = pkg_mod.__name__ + "." + mod_name
        modules.append(importutils.import_module(fq_name))

    return modules 
Example #19
Source File: shell.py    From python-harborclient with Apache License 2.0 5 votes vote down vote up
def get_subcommand_parser(self, version, do_help=False, argv=None):
        parser = self.get_base_parser(argv)

        self.subcommands = {}
        subparsers = parser.add_subparsers(metavar='<subcommand>')

        actions_module = importutils.import_module(
            "harborclient.v%s.shell" % version.ver_major)

        self._find_actions(subparsers, actions_module, version, do_help)
        self._find_actions(subparsers, self, version, do_help)
        self._add_bash_completion_subparser(subparsers)

        return parser 
Example #20
Source File: base.py    From manila with Apache License 2.0 5 votes vote down vote up
def __init__(self, db_driver=None):
        super(Base, self).__init__()
        if not db_driver:
            db_driver = CONF.db_driver
        self.db = importutils.import_module(db_driver)  # pylint: disable=C0103 
Example #21
Source File: loadables.py    From zun with Apache License 2.0 5 votes vote down vote up
def _get_classes_from_module(self, module_name):
        """Get the classes from a module that match the type we want."""
        classes = []
        module = importutils.import_module(module_name)
        for obj_name in dir(module):
            # Skip objects that are meant to be private.
            if obj_name.startswith('_'):
                continue
            itm = getattr(module, obj_name)
            if self._is_correct_class(itm):
                classes.append(itm)
        return classes 
Example #22
Source File: utils.py    From eclcli with Apache License 2.0 5 votes vote down vote up
def import_versioned_module(version, submodule=None):
    module = 'monitoringclient.v%s' % version

    if submodule:
        module = '.'.join((module, submodule))
    return importutils.import_module(module) 
Example #23
Source File: utils.py    From eclcli with Apache License 2.0 5 votes vote down vote up
def import_versioned_module(version, submodule=None):
    module = 'heatclient.v%s' % version
    if submodule:
        module = '.'.join((module, submodule))
    return importutils.import_module(module) 
Example #24
Source File: driver.py    From magnum with Apache License 2.0 5 votes vote down vote up
def get_version_info(self, stack):
        stack_param = self.template_def.get_heat_param(
            cluster_attr='coe_version')
        if stack_param:
            self.cluster.coe_version = stack.parameters[stack_param]

        version_module_path = self.template_def.driver_module_path+'.version'
        try:
            ver = importutils.import_module(version_module_path)
            container_version = ver.container_version
        except Exception:
            container_version = None
        self.cluster.container_version = container_version 
Example #25
Source File: test_profiler.py    From magnum with Apache License 2.0 5 votes vote down vote up
def test_all_public_methods_are_traced(self):
        profiler_opts.set_defaults(conf.CONF)
        self.config(enabled=True,
                    group='profiler')

        classes = [
            'magnum.conductor.api.API',
            'magnum.conductor.api.ListenerAPI',
            'magnum.conductor.handlers.ca_conductor.Handler',
            'magnum.conductor.handlers.cluster_conductor.Handler',
            'magnum.conductor.handlers.conductor_listener.Handler',
            'magnum.conductor.handlers.indirection_api.Handler',
            'magnum.service.periodic.MagnumPeriodicTasks',
        ]
        for clsname in classes:
            # give the metaclass and trace_cls() decorator a chance to patch
            # methods of the classes above
            six.reload_module(
                importutils.import_module(clsname.rsplit('.', 1)[0]))
            cls = importutils.import_class(clsname)

            for attr, obj in cls.__dict__.items():
                # only public methods are traced
                if attr.startswith('_'):
                    continue
                # only checks callables
                if not (inspect.ismethod(obj) or inspect.isfunction(obj)):
                    continue
                # osprofiler skips static methods
                if isinstance(obj, staticmethod):
                    continue

                self.assertTrue(getattr(obj, '__traced__', False), obj) 
Example #26
Source File: policy.py    From magnum with Apache License 2.0 5 votes vote down vote up
def add_policy_attributes(target):
    """Adds extra information for policy enforcement to raw target object"""
    context = importutils.import_module('magnum.common.context')
    admin_context = context.make_admin_context()
    admin_osc = clients.OpenStackClients(admin_context)
    trustee_domain_id = admin_osc.keystone().trustee_domain_id
    target['trustee_domain_id'] = trustee_domain_id
    return target 
Example #27
Source File: manager.py    From manila with Apache License 2.0 5 votes vote down vote up
def setup_rados():
    global rados
    if not rados:
        try:
            rados = importutils.import_module('rados')
        except ImportError:
            raise exception.ShareBackendException(
                _("python-rados is not installed")) 
Example #28
Source File: winrm_helper.py    From manila with Apache License 2.0 5 votes vote down vote up
def setup_winrm():
    global winrm
    if not winrm:
        try:
            winrm = importutils.import_module('winrm')
        except ImportError:
            raise exception.ShareBackendException(
                _("PyWinrm is not installed")) 
Example #29
Source File: test_profiler.py    From zun with Apache License 2.0 5 votes vote down vote up
def test_all_public_methods_are_traced(self):
        profiler_opts.set_defaults(conf.CONF)
        self.config(enabled=True,
                    group='profiler')

        classes = [
            'zun.compute.api.API',
            'zun.compute.rpcapi.API',
        ]
        for clsname in classes:
            # give the metaclass and trace_cls() decorator a chance to patch
            # methods of the classes above
            imp.reload(
                importutils.import_module(clsname.rsplit('.', 1)[0]))
            cls = importutils.import_class(clsname)

            for attr, obj in cls.__dict__.items():
                # only public methods are traced
                if attr.startswith('_'):
                    continue
                # only checks callables
                if not (inspect.ismethod(obj) or inspect.isfunction(obj)):
                    continue
                # osprofiler skips static methods
                if isinstance(obj, staticmethod):
                    continue

                self.assertTrue(getattr(obj, '__traced__', False), obj) 
Example #30
Source File: opts.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def datasources_opts():

    top = os.getcwd()

    datasources = _normalize_path_to_datasource_name(
        _filter_folders_containing_transformer(_get_datasources_folders(top)),
        top)

    return [(datasource, module.OPTS) for datasource in datasources
            for module in
            [importutils.import_module(DATASOURCES_PATH + datasource)]
            if 'OPTS' in vars(module)]