Load plugins from `plugins_package` module.
325907
def load_plugins(self, plugins_package):
        '''  '''
        try:
            # Resolve directory in the filesystem
            plugin_dir = find_spec(plugins_package).submodule_search_locations[0]
        except ImportError:
            logger.error(
                "Could not load plugins package '%(pkg)s'", {'pkg': plugins_package}
            )
            return

        for module_path in self._get_plugin_module_paths(plugin_dir):
            # Load the module dynamically
            spec = find_spec('{}.{}'.format(plugins_package, module_path))
            m = module_from_spec(spec)
            spec.loader.exec_module(m)

            # Get classes from module and extract the plugin classes
            classes = inspect.getmembers(m, predicate=inspect.isclass)
            for _, klass in classes:
                # Avoid imports processing
                if klass.__module__ != spec.name:
                    continue

                # Avoid classes not ending in Plugin
                if not klass.__name__.endswith('Plugin'):
                    continue

                instance = klass()
                if self._is_plugin_ok(instance):
                    self.plugins.add(instance)
1243395
def load_plugin(self, manifest, *args):
        
        if self.get_plugin_loaded(manifest["name"]):
            self._logger.debug("Plugin {} is already loaded.".format(manifest["name"]))
            return
        try:
            self._logger.debug("Attempting to load plugin {}.".format(manifest["name"]))
            for dependency in manifest.get("dependencies", []):
                if not self.get_plugin_loaded(dependency):
                    self._logger.debug("Must load dependency {} first.".format(dependency))
                    if self.get_manifest(dependency) is None:
                        self._logger.error("Dependency {} could not be found.".format(dependency))
                    else:
                        self.load_plugin(self.get_manifest(dependency), *args)

            not_loaded = [i for i in manifest.get("dependencies", []) if not self.get_plugin_loaded(i)]
            if len(not_loaded) != 0:
                self._logger.error("Plugin {} failed to load due to missing dependencies. Dependencies: {}".format(
                    manifest["name"], ", ".join(not_loaded)
                ))
                return

            if PY3:
                spec = importlib.util.spec_from_file_location(
                    manifest.get("module_name", manifest["name"].replace(" ", "_")),
                    os.path.join(manifest["path"], manifest.get("main_path", "__init__.py"))
                )
                module = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(module)
            else:
                module = imp.load_source(
                    manifest.get("module_name", manifest["name"].replace(" ", "_")),
                    os.path.join(manifest["path"], manifest.get("main_path", "__init__.py"))
                )

            module_class = manifest.get("main_class", "Plugin")
            plugin_class = getattr(module, module_class)
            if issubclass(plugin_class, self._plugin_class):
                plugin = plugin_class(manifest, *args)
            else:
                self._logger.error("Failed to load {} due to invalid baseclass.".format(manifest["name"]))
                return
            self._plugins[manifest["name"]] = plugin
            self._modules[manifest["name"]] = module

            self._logger.debug("Plugin {} loaded.".format(manifest["name"]))

        except:
            exc_path = os.path.join(manifest["path"], "error.log")
            with open(exc_path, "w") as f:
                f.write(traceback.format_exc(5))
            self._logger.error("Failed to load plugin {}. Error log written to {}.".format(manifest["name"], exc_path))
562750
def load_plugin(self, p):
        
        if p.is_loaded():
            return
        # load required plugins first
        reqnames = p.required
        reqplugins = []
        for name in reqnames:
            try:
                reqplugins.append(self.__plugins[name])
            except KeyError as e:
                log.error("Required Plugin %s not found. Cannot load %s." % (name, p))
                raise errors.PluginInitError('Required Plugin %s not found. Cannot load %s. Reason: %s' % (name, p, e))
        for plug in reqplugins:
            try:
                self.load_plugin(plug)
            except errors.PluginInitError as e:
                log.error("Required Plugin %s could not be loaded. Cannot load %s" % (plug, p))
                raise errors.PluginInitError('Required Plugin %s could not be loaded. Cannot load %s. Reason: %s' % (plug,p, e))
        # load the actual plugin
        p._load()
        log.info('Initialized the plugin: %s' % p)
954066
def collect_plugins(self, modules=None):
        
        if modules is None:
            modules = self.get_loaded_modules()
        else:
            modules = util.return_list(modules)

        plugins = []
        for module in modules:
            module_plugins = [(item[1], item[0])
                              for item
                              in inspect.getmembers(module)
                              if item[1] and item[0] != '__builtins__']
            module_plugins, names = zip(*module_plugins)

            module_plugins = self._filter_modules(module_plugins, names)
            plugins.extend(module_plugins)
        return plugins
120397
def _load_plugin(self, plugin_script, args=None, config=None):
        """"""
        # The key is the plugin name
        # for example, the file glances_xxx.py
        # generate self._plugins_list["xxx"] = ...
        name = plugin_script[len(self.header):-3].lower()
        try:
            # Import the plugin
            plugin = __import__(plugin_script[:-3])
            # Init and add the plugin to the dictionary
            if name in ('help', 'amps', 'ports', 'folders'):
                self._plugins[name] = plugin.Plugin(args=args, config=config)
            else:
                self._plugins[name] = plugin.Plugin(args=args)
            # Set the disable_<name> to False by default
            if self.args is not None:
                setattr(self.args,
                        'disable_' + name,
                        getattr(self.args, 'disable_' + name, False))
        except Exception as e:
            # If a plugin can not be log, display a critical message
            # on the console but do not crash
            logger.critical("Error while initializing the {} plugin ({})".format(name, e))
            logger.error(traceback.format_exc())
1238516
def load_plugins(self):
        ''' 
        '''
        self._dbg("Loading plugins")
        if not self.active_plugins:
            self._dbg("No plugins specified in conf file")
            return  # nothing to load

        for plugin_path in self.active_plugins:
            self._dbg("Importing {}".format(plugin_path))

            if self.debug is True:
                # this makes the plugin fail with stack trace in debug mode
                cls = import_string(plugin_path)
            else:
                # otherwise we log the exception and carry on
                try:
                    cls = import_string(plugin_path)
                except ImportError as error:
                    logging.exception("Problem importing {} - {}".format(
                        plugin_path, error)
                    )

            plugin_config = self.config.get(cls.__name__, {})
            plugin = cls(slack_client=self.slack_client, plugin_config=plugin_config)  # instatiate!
            self.bot_plugins.append(plugin)
            self._dbg("Plugin registered: {}".format(plugin))
580015
def load_custom_tc_plugins(self, plugin_path=None):
        
        if not plugin_path:
            return
        directory = os.path.dirname(plugin_path)
        sys.path.append(directory)
        modulename = os.path.split(plugin_path)[1]
        # Strip of file extension.
        if "." in modulename:
            modulename = modulename[:modulename.rindex(".")]
        try:
            module = importlib.import_module(modulename)
        except ImportError:
            raise PluginException("Unable to import custom plugin information from {}.".format(
                plugin_path))
        for plugin_name, plugin_class in module.plugins_to_load.items():
            if issubclass(plugin_class, PluginBase):
                try:
                    self.register_tc_plugins(plugin_name, plugin_class())
                except PluginException as error:
                    self.logger.debug(error)
                    continue
540725
def load_limits(self, config=None):
        """"""
        # For each plugins, call the load_limits method
        for p in self._plugins:
            self._plugins[p].load_limits(config)
595655
def load_plugins(self):
        """"""
        from dyndnsc.plugins.builtin import PLUGINS
        for plugin in PLUGINS:
            self.add_plugin(plugin())
        super(BuiltinPluginManager, self).load_plugins()
472716
def load_all_plugins(self):
        """"""

        # Go through the existing python files in the plugin directory
        self.plugin_path = os.path.realpath(self.plugin_dir)
        sys.path.append(self.plugin_dir)
        print '<<< Plugin Manager >>>'
        for f in [os.path.join(self.plugin_dir, child) for child in os.listdir(self.plugin_dir)]:

            # Skip certain files
            if '.DS_Store' in f or '__init__.py' in f: 
                continue

            # Add the plugin
            self.add_plugin(f)
1374037
def add_modules(self, package):
        """"""
        for name in os.listdir(package.__path__[0]):
            if name.startswith('_'):
                continue
            name = name.split('.')[0]
            short = '|%s|' % name
            long = ':mod:`~%s.%s`' % (package.__package__, name)
            self._short2long[short] = long
13335
def loadPlugins(cls):
        
        plugs = getattr(cls, '_%s__plugins' % cls.__name__, None)
        if plugs is not None:
            return

        plugs = {}
        setattr(cls, '_%s__plugins' % cls.__name__, plugs)
        typ = cls.pluginRegisterType()

        for path in cls.pluginPath():
            base_package = projex.packageFromPath(path)
            base_path = os.path.normpath(projex.packageRootPath(path))

            # make sure it is at the front of the path
            if base_path in sys.path:
                sys.path.remove(base_path)

            sys.path.insert(0, base_path)
            processed = ['__init__']

            # load support for registries
            if typ & Plugin.Type.RegistryFile:
                files = glob.glob(os.path.join(path, '*/register.xml'))
                for file_ in files:
                    name = os.path.normpath(file_).split(os.path.sep)[-2]
                    processed.append(name)

                    try:
                        proxy = PluginProxy.fromFile(cls, file_)
                        cls.register(proxy)

                    except Exception, e:
                        name = projex.text.pretty(name)
                        err = Plugin(name)
                        err.setError(e)
                        err.setFilepath(file_)

                        cls.register(err)

                        # log the error
                        msg = "%s.plugin('%s') failed to load from %s."
                        logger.warning(msg % (cls.__name__, name, file_))
                        logger.error(e)

            # load support for packages
            if typ & Plugin.Type.Package:
                files = glob.glob(os.path.join(path, '*/__init__.py'))
                for file_ in files:
                    name = os.path.normpath(file_).split(os.path.sep)[-2]
                    if name in processed:
                        continue

                    processed.append(name)
                    package = '.'.join([base_package, name]).strip('.')
                    if not package:
                        continue

                    try:
                        __import__(package)

                    except Exception, e:
                        name = projex.text.pretty(name)
                        err = Plugin(name)
                        err.setError(e)
                        err.setFilepath(file_)

                        cls.register(err)

                        # log the error
                        msg = "%s.plugin('%s') failed to load from %s."
                        logger.warning(msg % (cls.__name__, name, file_))
                        logger.error(e)

            # load support for modules
            if typ & Plugin.Type.Module:
                files = glob.glob(os.path.join(path, '*.py'))
                for file_ in files:
                    name = os.path.basename(file_).split('.')[0]
                    if name in processed:
                        continue

                    processed.append(name)
                    package = '.'.join([base_package, name]).strip('.')
                    if not package:
                        continue

                    try:
                        __import__(package)

                    except Exception, e:
                        name = projex.text.pretty(name)
                        err = Plugin(name)
                        err.setError(e)
                        err.setFilepath(file_)

                        cls.register(err)

                        # log the error
                        msg = "%s.plugin('%s') failed to load from %s."
                        logger.warning(msg % (cls.__name__, name, file_))
                        logger.error(e)
972269
def reload_all_plugins(self, *args):
        
        for manifest in self._manifests[:]:
            if self.get_plugin(manifest["name"]) is not None:
                self.reload_plugin(manifest["name"], *args)
523984
def get_plugin_modules(plugins):
    
    if not plugins:
        raise MissingPluginNames("input plugin names are required")

    modules = []

    for plugin in plugins:
        short_name = PLUGIN_MAPPING.get(plugin.lower(), plugin.lower())
        full_path = '%s%s' % (module_prefix, short_name)
        modules.append(importlib.import_module(full_path))

    return tuple(modules)
392091
def load_models(module):
    """"""
    modules = _import_submodules(module)
    return {m for module in modules for m in filter(
        _check_model, (getattr(module, name) for name in dir(module))
    )}
639928
def import_plugin(self, plugin):
        '''
        
        '''
        names = [
            '%s%s%s' % (namespace, '' if namespace[-1] == '_' else '.', plugin)
            if namespace else
            plugin
            for namespace in self.namespaces
            ]

        for name in names:
            if name in sys.modules:
                return sys.modules[name]

        for name in names:
            try:
                __import__(name)
                return sys.modules[name]
            except (ImportError, KeyError):
                pass

        raise PluginNotFoundError(
            'No plugin module %r found, tried %r' % (plugin, names),
            plugin, names)
509392
def load(cls, partname, content_type, blob, package):
        
        return cls(partname, content_type, blob)