def test_updatePluginPlaces(self): class SpecificLocator(IPluginLocator): pass pm = PluginManager() pm.setPluginPlaces(["bla/bli"]) pm.updatePluginPlaces(["mif/maf"]) self.assertEqual(set(["bla/bli", "mif/maf"]), set(pm.getPluginLocator().plugins_places))
def load_plugins(): manager = PluginManager() manager.setPluginPlaces(["plugins"]) manager.collectPlugins() for plugin in manager.getAllPlugins(): plugin_types = plugin.plugin_object.get_registered_types( ) # type: Dict[str, bool] for p in plugin_types.keys(): if p.startswith("int"): chars_method_name = "chars_" + p chars_method = getattr(plugin.plugin_object, chars_method_name, None) if chars_method is None: print( "Plugin Error: Method '%s' is missing from plugin file '%s' for type '%s'" % (chars_method, plugin.path, p)) raise ValueError AsmIntTypes.valid_chars[p] = chars_method() verify_method_name = "verify_" + p verify_method = getattr(plugin.plugin_object, verify_method_name, None) if verify_method is None: print( "Plugin Error: Method '%s' is missing from plugin file '%s' for type '%s'" % (verify_method_name, plugin.path, p)) raise ValueError AsmIntTypes.verify_methods[p] = verify_method emit_method_name = "emit_" + p emit_method = getattr(plugin.plugin_object, emit_method_name, None) if emit_method is None: print( "Plugin Error: Method '%s' is missing from plugin file '%s' for type '%s'" % (emit_method_name, plugin.path, p)) raise ValueError AsmIntTypes.emit_methods[p] = emit_method elif p.startswith("label"): calc_method_name = "calc_" + p calc_method = getattr(plugin.plugin_object, calc_method_name, None) if calc_method is None: print( "Plugin Error: Method '%s' is missing from plugin file '%s' for type '%s'" % (calc_method_name, plugin.path, p)) raise ValueError AsmIntTypes.calc_methods[p] = calc_method AsmIntTypes.defined_types[p] = True return
def __init__(self): self.plugin_manager = PluginManager() self.loaded_plugin_list = [] self.loaded_plugin_objects = None self.plugin_db = Plugins.Plugins(mongodb) self.plugin_location = os.path.abspath( os.path.join(os.getcwd(), 'Plugins')) self.deleted_plugin_location = os.path.abspath( os.path.join(os.getcwd(), 'Plugins_deleted')) self.load_plugin()
def get_all_plugins(self, path, p_categories_filter=None): """ Returns all plugin objects as array available at the specified path provided as argument """ _pm = PluginManager(categories_filter=p_categories_filter) _pm.setPluginPlaces([path]) _pm.locatePlugins() plugins = _pm.loadPlugins() del _pm return plugins
def main(): # Load the plugins from the plugin directory. manager = PluginManager() manager.setPluginPlaces(["orthos/plugins"]) manager.collectPlugins() # Loop round the plugins and print their names. for plugin in manager.getAllPlugins(): print "Fo" plugin.plugin_object.print_name()
def __init__(self): self.extractors_plugins_directories = [ DefaultDirectory.extractors_plugins() ] self.extractors_pre_configurations_directories = [ DefaultDirectory.extractors_pre_configurations() ] self._plugin_manager = PluginManager() self._extractors_pre_configurations = {}
def init_plugin_manager(): global simplePluginManager if not holder.plugin_manager: logging.debug('init plugin manager') simplePluginManager = PluginManager(categories_filter={"bots": BotPlugin}) simplePluginManager.setPluginInfoExtension('plug') holder.plugin_manager = simplePluginManager else: simplePluginManager = holder.plugin_manager
def plugins(): # Load the plugins from the plugin directory. manager = PluginManager() manager.setPluginPlaces(["plugins"]) manager.collectPlugins() # Loop round the plugins and print their names. for p in manager.getAllPlugins(): p.plugin_object.print_name() p.plugin_object.activate()
def executa_providers(self, providers_path=None): print("Executando Providers") self.provider_manager = PluginManager() self.provider_manager.setPluginInfoExtension("tiss-provider") if not self.providers_path: self.providers_path = os.path.join(os.path.dirname(__file__), 'extensoes/providers') self.provider_manager.setPluginPlaces([self.providers_path]) self.provider_manager.collectPlugins() for plugin in self.provider_manager.getAllPlugins(): plugin.plugin_object.executa(objeto=self)
def machine_list(request, pluginName, data, page='front', theID=None): user = request.user title = None # Build the manager manager = PluginManager() # Tell it the default place(s) where to find plugins manager.setPluginPlaces([ settings.PLUGIN_DIR, os.path.join(settings.PROJECT_DIR, 'server/plugins') ]) # Load all plugins manager.collectPlugins() # get a list of machines (either from the BU or the group) if page == 'front': # get all machines machines = Machine.objects.all() if page == 'bu_dashboard': # only get machines for that BU # Need to make sure the user is allowed to see this business_unit = get_object_or_404(BusinessUnit, pk=theID) machine_groups = MachineGroup.objects.filter( business_unit=business_unit).prefetch_related('machine_set').all() if machine_groups.count() != 0: machines_unsorted = machine_groups[0].machine_set.all() for machine_group in machine_groups[1:]: machines_unsorted = machines_unsorted | machine_group.machine_set.all( ) else: machines_unsorted = None machines = machines_unsorted if page == 'group_dashboard': # only get machines from that group machine_group = get_object_or_404(MachineGroup, pk=theID) # check that the user has access to this machines = Machine.objects.filter(machine_group=machine_group) # send the machines and the data to the plugin for plugin in manager.getAllPlugins(): if plugin.name == pluginName: (machines, title) = plugin.plugin_object.filter_machines(machines, data) c = { 'user': user, 'machines': machines, 'req_type': page, 'title': title, 'bu_id': theID, 'request': request } return render_to_response('server/overview_list_all.html', c, context_instance=RequestContext(request))
def bu_dashboard(request, bu_id): user = request.user user_level = user.userprofile.level business_unit = get_object_or_404(BusinessUnit, pk=bu_id) bu = business_unit config_installed = 'config' in settings.INSTALLED_APPS if business_unit not in user.businessunit_set.all() and user_level != 'GA': print 'not letting you in ' + user_level return redirect(index) # Get the groups within the Business Unit machine_groups = business_unit.machinegroup_set.all() if user_level == 'GA' or user_level == 'RW': is_editor = True else: is_editor = False machines = utils.getBUmachines(bu_id) now = datetime.now() hour_ago = now - timedelta(hours=1) today = date.today() week_ago = today - timedelta(days=7) month_ago = today - timedelta(days=30) three_months_ago = today - timedelta(days=90) # Build the manager manager = PluginManager() # Tell it the default place(s) where to find plugins manager.setPluginPlaces([ settings.PLUGIN_DIR, os.path.join(settings.PROJECT_DIR, 'server/plugins') ]) # Load all plugins manager.collectPlugins() output = [] # Loop round the plugins and print their names. for plugin in manager.getAllPlugins(): data = {} data['name'] = plugin.name (data['html'], data['width']) = plugin.plugin_object.show_widget( 'bu_dashboard', machines, bu.id) output.append(data) output = utils.orderPluginOutput(output, 'bu_dashboard', bu.id) c = { 'user': request.user, 'machine_groups': machine_groups, 'is_editor': is_editor, 'business_unit': business_unit, 'user_level': user_level, 'output': output, 'config_installed': config_installed } return render_to_response('server/bu_dashboard.html', c, context_instance=RequestContext(request))
def initialize_plugins(self): self.__log.info("Collecting and loading plugins") try: plugin_manager = PluginManager() # TODO: change plugin descriptor extensions, plugin_manager.setPluginInfoExtension(AGENT_PLUGIN_EXT) plugin_manager.setCategoriesFilter({ CARTRIDGE_AGENT_PLUGIN: ICartridgeAgentPlugin, ARTIFACT_MGT_PLUGIN: IArtifactManagementPlugin }) plugin_manager.setPluginPlaces( [self.__config.read_property(constants.PLUGINS_DIR)]) plugin_manager.collectPlugins() # activate cartridge agent plugins plugins = plugin_manager.getPluginsOfCategory( CARTRIDGE_AGENT_PLUGIN) grouped_plugins = {} for plugin_info in plugins: self.__log.debug("Found plugin [%s] at [%s]" % (plugin_info.name, plugin_info.path)) plugin_manager.activatePluginByName(plugin_info.name) self.__log.info("Activated plugin [%s]" % plugin_info.name) mapped_events = plugin_info.description.split(",") for mapped_event in mapped_events: if mapped_event.strip() != "": if grouped_plugins.get(mapped_event) is None: grouped_plugins[mapped_event] = [] grouped_plugins[mapped_event].append(plugin_info) # activate artifact management plugins artifact_mgt_plugins = plugin_manager.getPluginsOfCategory( ARTIFACT_MGT_PLUGIN) for plugin_info in artifact_mgt_plugins: self.__log.debug( "Found artifact management plugin [%s] at [%s]" % (plugin_info.name, plugin_info.path)) plugin_manager.activatePluginByName(plugin_info.name) self.__log.info("Activated artifact management plugin [%s]" % plugin_info.name) return plugin_manager, grouped_plugins, artifact_mgt_plugins except ParameterNotFoundException as e: self.__log.exception( "Could not load plugins. Plugins directory not set: %s" % e) return None, None, None except Exception as e: self.__log.exception("Error while loading plugin: %s" % e) return None, None, None
def __init__(self, perturbations_path): self.plugin_manager = PluginManager( directories_list=[perturbations_path], categories_filter={'Perturbations': IPerturbation}, plugin_info_ext='perturbation') self.plugin_manager.collectPlugins() self.last_perturbation_index = -1 # None applied yet self.loaded_perturbations = [] self.iterator = None self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG)
def main(): # Load the plugins from the plugin directory. manager = PluginManager() manager.setPluginPlaces(["storage_plugin/consul"]) manager.collectPlugins() # Loop round the plugins and print their names. for plugin in manager.getAllPlugins(): # plugin.plugin_object.put_record('ikepolicies',Dog('12345','hello')) plugin.plugin_object.get_record('ikepolicies', '12345') plugin.plugin_object.get_record('ikepolicies', 'hello', 'name')
def __init__(self, config: Config): self.config = config self.logger = colorlog.getLogger('mangekyou:pluginloader') self.logger.addHandler(self.config.handler) self.manager = PluginManager( categories_filter=self.config.categories_filter) self.manager.setPluginPlaces([self.config.plugins_folder]) self.logger.debug( f"Searching for plugins in {self.config.plugins_folder}")
def main(): global p # Load the plugins from the plugin directory. manager = PluginManager() manager.setPluginPlaces(["plugins"]) manager.collectPlugins() # Loop round the plugins and print their names. for plugin in manager.getAllPlugins(): p = plugin.plugin_object.print_name() print("path is:", p) plugin.plugin_object.convert_from_xml(p)
def init_manager(): anl = PluginFileAnalyzerMathingRegex('custom_res_handler_plugins', r'^[A-Za-z0-9]+\.py$') res = PluginFileLocator(plugin_info_cls=CFCustomResourceHandler) res.setAnalyzers([anl]) manager = PluginManager( plugin_locator=res, categories_filter={'CFHandlers': CFCustomResourceHandler}) manager.setPluginPlaces([dirname(__file__) + '/plugins']) manager.collectPlugins() return manager
def get_plugin(self, path, p_categories_filter=None): """ Returns a plugins available at specified path and of category provided as argument """ _pm = PluginManager(categories_filter=p_categories_filter) _pm.setPluginPlaces([path]) _pm.locatePlugins() plugins = _pm.loadPlugins() plugin = plugins[0].plugin_object del _pm del plugins return plugin
def setUp(self): """ init """ # create the plugin manager self.simplePluginManager = PluginManager(directories_list=[ os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins") ]) # load the plugins that may be found self.simplePluginManager.collectPlugins() # Will be used later self.plugin_info = None
def __init__(self, plugin_dirs=[]): logging.info( "Initializing with plugin directories: {!r}".format(plugin_dirs)) self.plugin_manager = PluginManager(directories_list=plugin_dirs, plugin_info_ext='octoplugin') self.plugin_manager.collectPlugins() for plugin in self.get_plugins(include_inactive=True).values(): # Bind the plugin object so the plugin can refer to it via self plugin.plugin_object.plugin_object = plugin # And bind it's configparser object separately as well for a cleaner API plugin.plugin_object.plugin_config = plugin.details
def test_setPluginInfoClass_with_strategies(self): class SpecificPluginInfo(PluginInfo): pass class SpecificLocator(IPluginLocator): def setPluginInfoClass(self,cls,name): if not hasattr(self,"icls"): self.icls = {} self.icls[name] = cls loc = SpecificLocator() pm = PluginManager(plugin_locator=loc) pm.setPluginInfoClass(SpecificPluginInfo,["mouf","hop"]) self.assertEqual({"mouf":SpecificPluginInfo,"hop":SpecificPluginInfo},loc.icls)
def testTwoStepsLoadWithError(self): """ Test loading the plugins in two steps in order to collect more deltailed informations and take care of an erroneous plugin. """ spm = PluginManager(directories_list=[ os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins") ], plugin_info_ext="yapsy-error-plugin") # trigger the first step to look up for plugins spm.locatePlugins() # make full use of the "feedback" the loadPlugins can give # - set-up the callback function that will be called *before* # loading each plugin callback_infos = [] def preload_cbk(i_plugin_info): callback_infos.append(i_plugin_info) callback_after_infos = [] def postload_cbk(i_plugin_info): callback_after_infos.append(i_plugin_info) # - gather infos about the processed plugins (loaded or not) # and for the test, monkey patch the logger originalLogLevel = log.getEffectiveLevel() log.setLevel(logging.ERROR) errorLogCallFlag = [False] def errorMock(*args, **kwargs): errorLogCallFlag[0] = True originalErrorMethod = log.error log.error = errorMock try: loadedPlugins = spm.loadPlugins(callback=preload_cbk, callback_after=postload_cbk) finally: log.setLevel(originalLogLevel) log.error = originalErrorMethod self.assertTrue(errorLogCallFlag[0]) self.assertEqual(len(loadedPlugins), 1) self.assertEqual(len(callback_infos), 1) self.assertTrue(isinstance(callback_infos[0].error, tuple)) self.assertEqual(loadedPlugins[0], callback_infos[0]) self.assertTrue(issubclass(callback_infos[0].error[0], ImportError)) self.assertEqual(len(callback_after_infos), 0) # check that the getCategories works self.assertEqual(len(spm.getCategories()), 1) sole_category = spm.getCategories()[0] # check the getPluginsOfCategory self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 0)
def initialize(self): ''' Initializes variables, this should only be called once ''' logging.info("Weapon system initializing ...") self.plugin_manager = PluginManager() self.plugin_manager.setPluginPlaces(["plugins/"]) self.plugin_manager.setCategoriesFilter(FILTERS) self.plugin_manager.collectPlugins() self.plugins = {} logging.info("Loaded %d plugin(s)" % len(self.plugin_manager.getAllPlugins())) self.__cpu__() logging.info("Weapon system online, good hunting.")
def get_plugins(category_filter={}, plugin_places=['plugins']): pm = PluginManager(plugin_info_ext='plugin') # Normalize the paths to the location of this file. # XXX-ricarkol: there has to be a better way to do this. plugin_places = [misc.execution_path(x) for x in plugin_places] pm.setPluginPlaces(plugin_places) pm.setCategoriesFilter(category_filter) pm.collectPlugins() return pm.getAllPlugins()
def __init__(self, threads, kill_list, kill_list_lock, job_list, binpath, modulebin): self.threads = threads self.kill_list = kill_list self.kill_list_lock = kill_list_lock self.job_list = job_list # Running jobs self.binpath = binpath self.module_bin_path = modulebin self.root_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..')) self.plugin_path = os.path.join(self.root_path, "lib", "assembly", "plugins") self.pmanager = PluginManager() locator = self.pmanager.getPluginLocator() locator.setPluginInfoExtension('asm-plugin') self.pmanager.setPluginPlaces([self.plugin_path]) self.pmanager.collectPlugins() self.pmanager.locatePlugins() self.plugins = ['none'] num_plugins = len(self.pmanager.getAllPlugins()) if num_plugins == 0: raise Exception("No Plugins Found!") plugins = [] self.executables = {} for plugin in self.pmanager.getAllPlugins(): plugin.threads = threads self.plugins.append(plugin.name) plugin.plugin_object.setname(plugin.name) ## Check for installed binaries try: version = plugin.details.get('Documentation', 'Version') executables = plugin.details.items('Executables') full_execs = [(k, self.get_executable_path(v)) for k, v in executables] for binary in full_execs: if not os.path.exists(binary[1]): if float(version) < 1: logger.warn( 'Third-party binary does not exist for beta plugin: {} (v{}) -- {}' .format(plugin.name, version, binary[1])) else: raise Exception( 'ERROR: Third-party binary does not exist for beta plugin: {} (v{}) -- {}' .format(plugin.name, version, binary[1])) self.executables[plugin.name] = full_execs except ConfigParser.NoSectionError: pass plugins.append(plugin.name) logger.info("Plugins found [{}]: {}".format(num_plugins, sorted(plugins)))
def disabled_plugins(plugin_kind='main'): enabled_plugins = Plugin.objects.all() # Build the manager manager = PluginManager() # Tell it the default place(s) where to find plugins manager.setPluginPlaces([ settings.PLUGIN_DIR, os.path.join(settings.PROJECT_DIR, 'server/plugins') ]) # Load all plugins manager.collectPlugins() output = [] if plugin_kind == 'main': for plugin in manager.getAllPlugins(): try: plugin_type = plugin.plugin_object.plugin_type() except: plugin_type = 'builtin' if plugin_type == 'builtin': try: item = Plugin.objects.get(name=plugin.name) except Plugin.DoesNotExist: output.append(plugin.name) if plugin_kind == 'report': for plugin in manager.getAllPlugins(): try: plugin_type = plugin.plugin_object.plugin_type() except: plugin_type = 'builtin' if plugin_type == 'report': try: item = Report.objects.get(name=plugin.name) except Report.DoesNotExist: output.append(plugin.name) if plugin_kind == 'machine_detail': for plugin in manager.getAllPlugins(): try: plugin_type = plugin.plugin_object.plugin_type() except: plugin_type = 'builtin' if plugin_type == 'machine_detail': try: item = MachineDetailPlugin.objects.get(name=plugin.name) except MachineDetailPlugin.DoesNotExist: output.append(plugin.name) return output
def __init__(self): self.template_system = self self.invariant = False self.debug = True self.config = { 'DISABLED_PLUGINS': [], 'EXTRA_PLUGINS': [], 'DEFAULT_LANG': 'en', 'MARKDOWN_EXTENSIONS': [ 'markdown.extensions.fenced_code', 'markdown.extensions.codehilite' ], 'TRANSLATIONS_PATTERN': '{path}.{lang}.{ext}', 'LISTINGS_FOLDERS': { 'listings': 'listings' }, 'TRANSLATIONS': { 'en': '' }, } self.EXTRA_PLUGINS = self.config['EXTRA_PLUGINS'] self.plugin_manager = PluginManager( categories_filter={ "Command": Command, "Task": Task, "LateTask": LateTask, "TemplateSystem": TemplateSystem, "PageCompiler": PageCompiler, "TaskMultiplier": TaskMultiplier, "CompilerExtension": CompilerExtension, "MarkdownExtension": MarkdownExtension, "RestExtension": RestExtension }) self.shortcode_registry = {} self.plugin_manager.setPluginInfoExtension('plugin') places = [ os.path.join(os.path.dirname(nikola.utils.__file__), 'plugins') ] self.plugin_manager.setPluginPlaces(places) self.plugin_manager.collectPlugins() self.compiler_extensions = self._activate_plugins_of_category( "CompilerExtension") self.timeline = [FakePost(title='Fake post', slug='fake-post')] self.debug = True self.rst_transforms = [] self.post_per_input_file = {} # This is to make plugin initialization happy self.template_system = self self.name = 'mako'
def parse_url(url): plugins_folder = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'plugins') manager = PluginManager() manager.setPluginPlaces([plugins_folder]) manager.collectPlugins() plugins = [ x for x in manager.getAllPlugins() if hasattr(x.plugin_object, 'parse_url') ] for plugin in plugins: for item in plugin.plugin_object.parse_url(url): yield item
def __init__(self): super().__init__() self.manager = PluginManager(plugin_info_ext="marinheiro-test", directories_list=[ os.path.join( os.path.dirname(__file__), "tests") ], categories_filter={ "Basic": marinheiro.tests.BasicTest, "Web": marinheiro.tests.WebTest, }) self.manager.collectPlugins()
def __get_mgr(cls): if not cls.__plugin_mgr: analyzer = PluginFileAnalyzerMathingRegexWithInfoProperty( 'file_name_analyzer', r'^.*\.py$') mgr = PluginManager(categories_filter=cls.__categories) mgr.setPluginPlaces(["plugins"]) mgr.getPluginLocator().removeAllAnalyzer() mgr.getPluginLocator().appendAnalyzer(analyzer) mgr.locatePlugins() mgr.loadPlugins() cls.__plugin_mgr = mgr return cls.__plugin_mgr