Exemple #1
0
def loadPlugins(pluginfldr,hivesdict):
    """
    Enumerate plugins in the specified directory and return the populated
    plugin manager and a list of the compatible plugins. Compatibility is
    determined by checking if the required hives were loaded sucessfully.
    """
    pluginmanager = PluginManager()
    pluginmanager.setPluginPlaces([pluginfldr])
    pluginmanager.collectPlugins()

    print ""
    logging.info("[PLUGINS IDENTIFIED: %s]" % len(pluginmanager.getAllPlugins()))

    compat_plugins = list()
    incompat_plugins = list()
    for plugin in pluginmanager.getAllPlugins():
        compat = 1
        for req in plugin.plugin_object.getRequirements():
            if (hivesdict[req][0] <> 1):
                compat = 0
                break
        if compat:
            compat_plugins.append(plugin.name)
        else:
            incompat_plugins.append(plugin.name)

    logging.info(" [%s] Compatible Plugins:" % len(compat_plugins))
    for plugin in compat_plugins:
        logging.info("  - %s" % plugin)
    logging.info(" [%s] Incompatible Plugins:" % len(incompat_plugins))
    for plugin in incompat_plugins:
        logging.info("  - %s" % plugin)

    return pluginmanager, compat_plugins
Exemple #2
0
def loadPlugins(root_folder, plugin_name, categories_filter):
    from yapsy.PluginManager import PluginManager

    plugin_dirs = []
    plugin_dirs.append(configuration.fabfile_basedir + '/.fabalicious/plugins')
    plugin_dirs.append(expanduser("~") + '/.fabalicious/plugins')
    plugin_dirs.append(root_folder + '/plugins')

    log.debug("Looking for %s-plugins in %s" %
              (plugin_name, ", ".join(plugin_dirs)))

    manager = PluginManager()
    manager.setPluginPlaces(plugin_dirs)
    manager.setCategoriesFilter(categories_filter)
    manager.collectPlugins()

    # Activate all loaded plugins
    for pluginInfo in manager.getAllPlugins():
        manager.activatePluginByName(pluginInfo.name)

    result = {}
    for plugin in manager.getAllPlugins():

        if hasattr(plugin.plugin_object, 'aliases') and isinstance(
                plugin.plugin_object.aliases, list):
            for alias in plugin.plugin_object.aliases:
                result[alias] = plugin.plugin_object
        elif hasattr(plugin.plugin_object, 'alias'):
            result[plugin.plugin_object.alias] = plugin.plugin_object
        else:
            result[plugin.name] = plugin.plugin_object
    return result
Exemple #3
0
class ProfilesManager(object):

    def __init__(self):
        self.plugin_location = [PROFILE_MODULE_DIR]
        self.pluginManager = PluginManager(plugin_info_ext="plugin")

        self.pluginManager.setPluginPlaces(self.plugin_location)
        self.pluginManager.collectPlugins()

    def modules_info(self):
        """
        Get information with regards to each modules loaded. It includes author, category, copyright, description,
        details, name, version and website.
        :return: information of all modules loaded
        """
        modules_info = {}
        for pluginInfo in self.pluginManager.getAllPlugins():
            modules_info[pluginInfo.name] = pluginInfo

        return modules_info

    def configForms(self, device_serial, module_name=""):
        """
        Get the configuration views of each modules to be displayed on web interface
        :return: dictionary of pluginInfo as key and form as value
        """
        if module_name:
            plugin = self.pluginManager.getPluginByName(name=module_name)
            configForms = plugin.plugin_object.get_view()
        else:
            configForms = {}
            for pluginInfo in self.pluginManager.getAllPlugins():
                form = pluginInfo.plugin_object.get_view()
                configForms[pluginInfo] = form

        return configForms

    def run_simulation(self,option, profile_name, duration, device_serial, package_name, session):
        """
        Run profile simulation script
        :return:
        """
        plugin = self.pluginManager.getPluginByName(name=profile_name)
        if option == RANDOM_INTERACTION:
            plugin.plugin_object.runSimulation(duration,package_name, random=True, device_serial=device_serial, session=session)
        elif option == SCRIPTED_PROFILE_INTERACTION:
            plugin.plugin_object.runSimulation(duration,package_name, random=False, device_serial=device_serial, session=session)



    def setup_device(self,module, params, device_serial):
        """
        install profile apk and profile app data onto device
        :return:
        """
        pluginInfo = self.pluginManager.getPluginByName(name=module)
        if pluginInfo.name == module:
            pluginInfo.plugin_object.prepare(params, device_serial)

        return True
Exemple #4
0
def loadPlugins(root_folder, plugin_name, categories_filter):
  from yapsy.PluginManager import PluginManager

  plugin_dirs = []
  plugin_dirs.append(configuration.fabfile_basedir + '/.fabalicious/plugins')
  plugin_dirs.append(expanduser("~") + '/.fabalicious/plugins')
  plugin_dirs.append(root_folder + '/plugins')

  log.debug("Looking for %s-plugins in %s" % (plugin_name, ", ".join(plugin_dirs)))

  manager = PluginManager()
  manager.setPluginPlaces(plugin_dirs)
  manager.setCategoriesFilter(categories_filter)
  manager.collectPlugins()

  # Activate all loaded plugins
  for pluginInfo in manager.getAllPlugins():
    manager.activatePluginByName(pluginInfo.name)

  result = {}
  for plugin in manager.getAllPlugins():

    if hasattr(plugin.plugin_object, 'aliases') and isinstance(plugin.plugin_object.aliases, list):
      for alias in plugin.plugin_object.aliases:
        result[alias] = plugin.plugin_object
    elif hasattr(plugin.plugin_object, 'alias'):
      result[plugin.plugin_object.alias] = plugin.plugin_object
    else:
      result[plugin.name] = plugin.plugin_object
  return result
class AlgorithmManager():
    def __init__(self):
        self._pluginManager = PluginManager()
        self._pluginManager.setPluginPlaces(config.PLUGIN_DIR)
        self._pluginManager.collectPlugins()
        for pluginInfo in self._pluginManager.getAllPlugins():
            self._pluginManager.activatePluginByName(pluginInfo.name)
            
    def get_alg_names(self):
        for plugin in self._pluginManager.getAllPlugins():
            plugin.plugin_object.print_name()
            
    def execute_calc(self, data):
        run = []
        if not self.__is_sequence(data):
            raise Exception('Data is no array!')
        for alg in self._pluginManager.getAllPlugins():
            result, prop = alg.plugin_object.calc(data)
            run.append({alg.name : (result, prop)})
        return run

    
    def __is_sequence(self, arg):
        return (not hasattr(arg, "strip") and
            hasattr(arg, "__getitem__") or
            hasattr(arg, "__iter__"))
                 
    
        
def main():
    # Yapsy uses Python’s standard logging module to record most important events and especially plugin loading failures.
    logging.basicConfig(level=logging.INFO)
    logging.getLogger('yapsy').setLevel(logging.DEBUG)  # Enable DEBUG logging during development

    # Build the manager
    simplePluginManager = PluginManager()

    # Tell it the directories it should look in to find plugins
    simplePluginManager.setPluginPlaces(['plugins'])

    # Tell it the file extension to use for PluginInfo files (INI format)
    simplePluginManager.setPluginInfoExtension('plug')

    # Load all plugins
    simplePluginManager.collectPlugins()

    # Activate all loaded plugins (calls activate method)
    for pluginInfo in simplePluginManager.getAllPlugins():
        # pluginInfo is a plugin_info object, which is typically an instance of IPlugin
        simplePluginManager.activatePluginByName(pluginInfo.name)

    # Loop through the plugins and call a custom method to print their names
    for plugin in simplePluginManager.getAllPlugins():
        plugin.plugin_object.print_name()
  def collect_data(self, **kwargs):
    self.logger.info("Begin collect_data")

    simplePluginManager = PluginManager()
    logging.getLogger('yapsy').setLevel(logging.DEBUG)
    simplePluginManager.setCategoriesFilter({
       "DataCollector": data_collector_plugin
       })

    # Tell it the default place(s) where to find plugins
    self.logger.debug("Plugin directories: %s" % (kwargs['data_collector_plugin_directories']))
    simplePluginManager.setPluginPlaces(kwargs['data_collector_plugin_directories'])

    simplePluginManager.collectPlugins()

    plugin_cnt = 0
    plugin_start_time = time.time()
    for plugin in simplePluginManager.getAllPlugins():
      self.logger.info("Starting plugin: %s" % (plugin.name))
      if plugin.plugin_object.initialize_plugin(details=plugin.details):
        plugin.plugin_object.start()
      else:
        self.logger.error("Failed to initialize plugin: %s" % (plugin.name))
      plugin_cnt += 1

    #Wait for the plugings to finish up.
    self.logger.info("Waiting for %d plugins to complete." % (plugin_cnt))
    for plugin in simplePluginManager.getAllPlugins():
      plugin.plugin_object.join()
    self.logger.info("%d Plugins completed in %f seconds" % (plugin_cnt, time.time() - plugin_start_time))
Exemple #8
0
def init_request_validators(gn_env: GNEnvironment) -> None:
    from yapsy.PluginManager import PluginManager
    logging.getLogger('yapsy').setLevel(
        gn_env.config.get(ConfigKeys.LOG_LEVEL, logging.INFO))

    plugin_manager = PluginManager()
    plugin_manager.setPluginPlaces(['dino/validation/events'])
    plugin_manager.collectPlugins()

    for pluginInfo in plugin_manager.getAllPlugins():
        plugin_manager.activatePluginByName(pluginInfo.name)
        gn_env.event_validators[pluginInfo.name] = pluginInfo.plugin_object

    validation = gn_env.config.get(ConfigKeys.VALIDATION, None)
    if validation is None:
        return

    for key in validation.keys():
        if key not in gn_env.event_validator_map:
            gn_env.event_validator_map[key] = list()
        plugins = validation[key].copy()
        validation[key] = dict()
        for plugin_info in plugins:
            plugin_name = plugin_info.get('name')
            validation[key][plugin_name] = plugin_info
            try:
                gn_env.event_validator_map[key].append(
                    gn_env.event_validators[plugin_name])
            except KeyError:
                raise KeyError('specified plugin "%s" does not exist' % key)

    gn_env.config.set(ConfigKeys.VALIDATION, validation)

    for pluginInfo in plugin_manager.getAllPlugins():
        pluginInfo.plugin_object.setup(gn_env)
Exemple #9
0
def loadPlugins(pluginfldr, hivesdict):
    """
    Enumerate plugins in the specified directory and return the populated
    plugin manager and a list of the compatible plugins. Compatibility is
    determined by checking if the required hives were loaded sucessfully.
    """
    pluginmanager = PluginManager()
    pluginmanager.setPluginPlaces([pluginfldr])
    pluginmanager.collectPlugins()

    print ""
    logging.info("[PLUGINS IDENTIFIED: %s]" %
                 len(pluginmanager.getAllPlugins()))

    compat_plugins = list()
    incompat_plugins = list()
    for plugin in pluginmanager.getAllPlugins():
        compat = 1
        for req in plugin.plugin_object.getRequirements():
            if (hivesdict[req][0] <> 1):
                compat = 0
                break
        if compat:
            compat_plugins.append(plugin.name)
        else:
            incompat_plugins.append(plugin.name)

    logging.info(" [%s] Compatible Plugins:" % len(compat_plugins))
    for plugin in compat_plugins:
        logging.info("  - %s" % plugin)
    logging.info(" [%s] Incompatible Plugins:" % len(incompat_plugins))
    for plugin in incompat_plugins:
        logging.info("  - %s" % plugin)

    return pluginmanager, compat_plugins
    def collect_data(self, **kwargs):
        self.logger.info("Begin collect_data")
        try:
            simplePluginManager = PluginManager()
            logging.getLogger('yapsy').setLevel(logging.DEBUG)
            simplePluginManager.setCategoriesFilter(
                {"DataCollector": data_collector_plugin})

            # Tell it the default place(s) where to find plugins
            self.logger.debug("Plugin directories: %s" %
                              (kwargs['data_collector_plugin_directories']))
            yapsy_logger = logging.getLogger('yapsy')
            yapsy_logger.setLevel(logging.DEBUG)
            #yapsy_logger.parent.level = logging.DEBUG
            yapsy_logger.disabled = False

            simplePluginManager.setPluginPlaces(
                kwargs['data_collector_plugin_directories'])

            simplePluginManager.collectPlugins()

            output_queue = Queue()
            plugin_cnt = 0
            plugin_start_time = time.time()
            for plugin in simplePluginManager.getAllPlugins():
                plugin_start_time = time.time()
                self.logger.info("Starting plugin: %s" % (plugin.name))
                if plugin.plugin_object.initialize_plugin(
                        details=plugin.details,
                        queue=output_queue,
                        begin_date=kwargs['begin_date']):
                    plugin.plugin_object.start()
                    self.logger.info("Waiting for %s plugin to complete." %
                                     (plugin.name))
                    plugin.plugin_object.join()
                    self.logger.info(
                        "%s plugin to completed in %f seconds." %
                        (plugin.name, time.time() - plugin_start_time))
                else:
                    self.logger.error("Failed to initialize plugin: %s" %
                                      (plugin.name))
                plugin_cnt += 1

            #Wait for the plugings to finish up.
            self.logger.info("Waiting for %d plugins to complete." %
                             (plugin_cnt))
            for plugin in simplePluginManager.getAllPlugins():
                plugin.plugin_object.join()

            while not output_queue.empty():
                results = output_queue.get()
                if results[0] == data_result_types.SAMPLING_DATA_TYPE:
                    self.bacteria_sample_data = results[1]

            self.logger.info("%d Plugins completed in %f seconds" %
                             (plugin_cnt, time.time() - plugin_start_time))
        except Exception as e:
            self.logger.exception(e)
Exemple #11
0
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
Exemple #12
0
    def output_results(self, **kwargs):

        self.logger.info("Begin run_output_plugins")

        simplePluginManager = PluginManager()
        logging.getLogger('yapsy').setLevel(logging.DEBUG)
        simplePluginManager.setCategoriesFilter(
            {"OutputResults": data_collector_plugin})

        # Tell it the default place(s) where to find plugins
        self.logger.debug("Plugin directories: %s" %
                          (kwargs['output_plugin_directories']))
        simplePluginManager.setPluginPlaces(
            kwargs['output_plugin_directories'])
        yapsy_logger = logging.getLogger('yapsy')
        yapsy_logger.setLevel(logging.DEBUG)
        # yapsy_logger.parent.level = logging.DEBUG
        yapsy_logger.disabled = False

        simplePluginManager.collectPlugins()

        plugin_cnt = 0
        plugin_start_time = time.time()
        for plugin in simplePluginManager.getAllPlugins():
            try:
                self.logger.info("Starting plugin: %s" % (plugin.name))
                if plugin.plugin_object.initialize_plugin(
                        details=plugin.details,
                        prediction_date=kwargs['prediction_date'].astimezone(
                            timezone("US/Eastern")).strftime(
                                "%Y-%m-%d %H:%M:%S"),
                        execution_date=kwargs['prediction_run_date'].strftime(
                            "%Y-%m-%d %H:%M:%S"),
                        ensemble_tests=kwargs['site_model_ensemble']):
                    plugin.plugin_object.start()
                    plugin_cnt += 1
                else:
                    self.logger.error("Failed to initialize plugin: %s" %
                                      (plugin.details))
            except Exception as e:
                self.logger.exception(e)
        #Wait for the plugings to finish up.
        self.logger.info("Waiting for %d plugins to complete." % (plugin_cnt))
        for plugin in simplePluginManager.getAllPlugins():
            plugin.plugin_object.join()
            plugin.plugin_object.finalize()

        self.logger.debug("%d output plugins run in %f seconds" %
                          (plugin_cnt, time.time() - plugin_start_time))
        self.logger.info("Finished output_results")
    def test_plugin_locator_with_manager(self):
        """Test cases for plugin locator.

        Uses custom PluginLocator inside PluginManager.
        """
        from drop.plugins import DropPluginLocator
        from yapsy.PluginManager import PluginManager

        pm = PluginManager(plugin_locator=DropPluginLocator())

        # TODO: Create some dummy plugins to be found

        pm.collectPlugins()
        pm.getAllPlugins()
Exemple #14
0
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 != 'report':
                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
Exemple #15
0
def create(message):
    pluginManager = PluginManager()
    pluginManager.setPluginPlaces(
        [current_app.config["PLUGINS_PATH"] + os.sep + "validators"])
    pluginManager.collectPlugins()

    for pluginInfo in pluginManager.getAllPlugins():
        pluginManager.activatePluginByName(pluginInfo.name)

    pluginInfo = pluginManager.getPluginByName(message['name'])

    if pluginInfo != None:
        raise "Lo sentimos pero el nombre del plugin que ya esta siendo utilizado"

    plugin_info_file = open(
        current_app.config["PLUGINS_PATH"] + os.sep + "validators" + os.sep +
        str(message["name"]) + ".yapsy-plugin", "w")
    plugin_file = open(
        current_app.config["PLUGINS_PATH"] + os.sep + "validators" + os.sep +
        str(message["name"]) + ".py", "w")
    plugin_info_file.write(
        str(message["file_info"]).decode("base64", errors="strict"))
    plugin_file.write(str(message["data"]).decode("base64"))
    plugin_info_file.write(
        str('Organization = ' + current_app.config['ORGANIZATION_CONTEXT_ID'] +
            ' - ' + current_app.config['ORGANIZATION_CONTEXT_DESC']))
    plugin_info_file.close()
    plugin_file.close()
Exemple #16
0
def getBankRates():
    # Load the plugins from the plugin directory.
	manager = PluginManager()
	# Server
	# manager.setPluginPlaces(["./dev/liborWatch/server/plugins"])
	# Dev
	# manager.setPluginPlaces(["./plugins"])
	# Local
	manager.setPluginPlaces(["./dev/NextLevelApps/liborWatch/server/plugins"])

	manager.collectPlugins()
	today = datetime.date.today().strftime('%Y-%m-%d')

    # Loop round the plugins and get the bank rates
	for plugin in manager.getAllPlugins():
		rates = plugin.plugin_object.getRates()
		print(rates);
		if(len(rates) != 10):
			print('Error: We did not get 10 rates from the plugin ' + plugin.name + ' - ' + str(len(rates)))
			return

		newRate = []
		iCnt = 0;
		for rate in rates:
			iCnt = iCnt + 1
			newRate.append((plugin.name, today, iCnt, rate))
#			print('execute insert statement ' + plugin.name, str(today), str(iCnt), str(rate))

		con = sqlite3.connect('liborWatch.sqlite')
		with con:
			cur = con.cursor()
			cur.execute("CREATE TABLE IF NOT EXISTS BankRate(id INTEGER PRIMARY KEY, bankName TEXT, date TEXT, fixedForYears INTEGER, rate REAL)")
			cur.executemany("INSERT INTO BankRate VALUES(NULL, ?, ?, ?, ?)", newRate)
Exemple #17
0
    def __run_reporting_generator(self):

        # options
        options = dict()

        # Build the PluginManager
        reportingPluginManager = PluginManager()
        reportingPluginManager.setPluginPlaces(["reporting"])
        reportingPluginManager.collectPlugins()

        # Trigger run from the "Reporting" plugins
        for pluginInfo in sorted(reportingPluginManager.getAllPlugins(),
                                 key=lambda PluginInfo: PluginInfo.name):
            reportingModulG = pluginInfo.plugin_object
            reportingModulG.set_task(self.task)

            # Give it the the relevant reporting.conf section.
            try:
                options = self.cfgReporting.get(pluginInfo.name)
                reportingModulG.set_options(options)
            except Exception:
                log.error(
                    "Reporting module %s not found in configuration file",
                    pluginInfo.name)

            # If the processing module is disabled in the config, skip it.
            if not options.enabled:
                continue

            log.debug("Run Reporting: " + pluginInfo.name)

            yield reportingModulG
Exemple #18
0
 def __run_reporting_generator(self):
             
     # options
     options = dict()
     
     # Build the PluginManager
     reportingPluginManager = PluginManager()
     reportingPluginManager.setPluginPlaces(["reporting"])
     reportingPluginManager.collectPlugins()
     
     # Trigger run from the "Reporting" plugins
     for pluginInfo in sorted(reportingPluginManager.getAllPlugins(), key=lambda PluginInfo: PluginInfo.name):
         reportingModulG = pluginInfo.plugin_object
         reportingModulG.set_task(self.task)
         
         # Give it the the relevant reporting.conf section.
         try:
             options = self.cfgReporting.get(pluginInfo.name)
             reportingModulG.set_options(options)
         except Exception:
             log.error("Reporting module %s not found in configuration file", pluginInfo.name)  
             
         # If the processing module is disabled in the config, skip it.
         if not options.enabled:
             continue
         
         log.debug("Run Reporting: " + pluginInfo.name)
         
         yield reportingModulG
Exemple #19
0
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
        if user.userprofile.level == 'GA':
            machines = Machine.objects.all()
        else:
            machines = Machine.objects.none()
            for business_unit in user.businessunit_set.all():
                for group in business_unit.machinegroup_set.all():
                    machines = machines | group.machine_set.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))
Exemple #20
0
def run():
    logging.basicConfig(level=logging.INFO)

    os.chdir('/home/mjolnir/git/PURIKURA')

    # H A N D L E  P L U G I N S
    pm = PluginManager()
    pm.setPluginPlaces(['./pyrikura/plugins'])
    pm.collectPlugins()

    for pi in pm.getAllPlugins():
        logging.info('loading plugin %s', pi.name)
        pm.activatePluginByName(pi.name)

    brokers = {}
    nodes = build()
    head = nodes[0]

    for node in nodes:
        brokers[node] = node.load(pm)

    for node, broker in brokers.items():
        for other in node._listening:
            broker.subscribe(brokers[other])

    start = time.time()
    last_time = 0
    shots = 0
    last_trigger = 0
    for broker in itertools.cycle(brokers.values()):
        broker.update()
Exemple #21
0
def main():
    # Read configuration
    config = SafeConfigParser(
        defaults = {'port':'15915',
                    'plugins_directory':'./plugins',
                    'plugins_enabled':'',
                   })
    config.read(['./conf/cm15d.conf',
                 '/etc/cm15d.conf',
                 '/etc/cm15d/cm15d.conf',
                 '/etc/cm15d/conf.d/local.conf',
                ])

    # Activate enabled plugins
    plugins = PluginManager()
    plugins.setPluginPlaces(config.get('cm15d', 'plugins_directory').split(','))
    plugins.collectPlugins()
    plugins_enabled = config.get('cm15d', 'plugins_enabled').split(',')

    for plugin in plugins.getAllPlugins():
        if plugin.name in plugins_enabled:
            plugins.activatePluginByName(plugin.name)
            print("Plugin %s enabled" % plugin.name)

    # Start server
    port = int(config.get('cm15d', 'port'))
    endpoint = TCP4ServerEndpoint(reactor, port)
    endpoint.listen(CM15DaemonFactory(plugins))
    print("Server listening on port %s" % port)
    reactor.run()
Exemple #22
0
def run():
    logging.basicConfig(level=logging.INFO)

    os.chdir('/home/mjolnir/git/PURIKURA')

    # H A N D L E  P L U G I N S
    pm = PluginManager()
    pm.setPluginPlaces(['./pyrikura/plugins'])
    pm.collectPlugins()

    for pi in pm.getAllPlugins():
        logging.info('loading plugin %s', pi.name)
        pm.activatePluginByName(pi.name)

    brokers = {}
    nodes = build()
    head = nodes[0]

    for node in nodes:
        brokers[node] = node.load(pm)

    for node, broker in brokers.items():
        for other in node._listening:
            broker.subscribe(brokers[other])

    start = time.time()
    last_time = 0
    shots = 0
    last_trigger = 0
    for broker in itertools.cycle(brokers.values()):
        broker.update()
Exemple #23
0
def main():
    # Read configuration
    config = SafeConfigParser(defaults={
        'port': '15915',
        'plugins_directory': './plugins',
        'plugins_enabled': '',
    })
    config.read([
        './conf/cm15d.conf',
        '/etc/cm15d.conf',
        '/etc/cm15d/cm15d.conf',
        '/etc/cm15d/conf.d/local.conf',
    ])

    # Activate enabled plugins
    plugins = PluginManager()
    plugins.setPluginPlaces(
        config.get('cm15d', 'plugins_directory').split(','))
    plugins.collectPlugins()
    plugins_enabled = config.get('cm15d', 'plugins_enabled').split(',')

    for plugin in plugins.getAllPlugins():
        if plugin.name in plugins_enabled:
            plugins.activatePluginByName(plugin.name)
            print("Plugin %s enabled" % plugin.name)

    # Start server
    port = int(config.get('cm15d', 'port'))
    endpoint = TCP4ServerEndpoint(reactor, port)
    endpoint.listen(CM15DaemonFactory(plugins))
    print("Server listening on port %s" % port)
    reactor.run()
Exemple #24
0
def execute(route, plugin, payload):

    logging.basicConfig()

    # Build the manager
    simplePluginManager = PluginManager()
    # Tell it the default place(s) where to find plugins
    print route
    simplePluginManager.setPluginPlaces(route)
    # Load all plugins
    simplePluginManager.collectPlugins()

    # Activate all loaded plugins
    for pluginInfo in simplePluginManager.getAllPlugins():
        simplePluginManager.activatePluginByName(pluginInfo.name)

    # for pluginInfo in simplePluginManager.getAllPlugins():
    #    var1,var2 = pluginInfo.plugin_object.execute()
    simplePluginManager.activatePluginByName(plugin)
    pluginInfo = simplePluginManager.getPluginByName(plugin)

    if pluginInfo is None:
        current_app.logger.error(
            "Lo sentimos pero no se ha podido cargar el plugin o el mismo no se ha encontrado"
        )
        raise Exception("No se ha podido cargar el plugin")
    return pluginInfo.plugin_object.execute(payload)
class PluginLoader:
    logger: Logger
    config: Config
    manager: PluginManager

    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 load_plugins(self) -> list:
        plugins = list()

        self.manager.collectPlugins()
        load = self.manager.getAllPlugins()
        for plugin in load:
            self.logger.debug(f"{plugin.name} loaded!")
            plugins.append(plugin)

        return plugins
Exemple #26
0
def main():
    simplePluginManager = PluginManager()
    simplePluginManager.setPluginPlaces(["plugins"])
    simplePluginManager.collectPlugins()

    for plugin in simplePluginManager.getAllPlugins():
        plugin.plugin_object.greetings()
Exemple #27
0
def main():
    parser = argparse.ArgumentParser(description='Validates file format')
    parser.add_argument('files', nargs='+',
                        help='files to be validated')
    parser.add_argument('--verbose', action='store_true',
                        default=False,
                        help='Shows help about validation')

    args = parser.parse_args()

    simplePluginManager = PluginManager()
    simplePluginManager.setPluginPlaces(["plugins"])
    simplePluginManager.collectPlugins()

    for filename in args.files:
        supported = False
        for plugin in simplePluginManager.getAllPlugins():
            methods = plugin.plugin_object
            if methods.should_manage(filename):
                supported = True
                try:
                    plugin.plugin_object.validate(filename)
                    print('%s sintax ok for %s' % (filename, plugin.name))
                    break
                except Exception as e:
                    print('Invalid file %s for %s' % (filename, plugin.name))
                    if args.verbose:
                        print(e)
        if not supported:
            print('%s cannot be validated' % filename)
Exemple #28
0
def reloadPlugins():
    global plugins
    simplePluginManager = PluginManager()
    simplePluginManager.setPluginPlaces(["modules"])
    simplePluginManager.collectPlugins()
    plugins = simplePluginManager.getAllPlugins()
    pluginsByPort()
Exemple #29
0
    def pane_data(self):
        list = []  # Holds the filter tuples (name, activated=True)

        # Get the default plugin directory, using XML
        path = os.path.expanduser("~")
        xml = xml_controller.Controller(path + "\.cxvrc.xml")
        xml.load_file()

        if os.path.exists(os.path.expanduser("~") + os.sep + "plugins"):
            default_dir = os.path.expanduser("~") + os.sep + "plugins"
        else:
            default_dir = self.dicom_view.get_main_dir() + os.sep + "plugins"

        if xml.get_plugin_directory() == "" or xml.get_plugin_directory() is None:
            directory = [default_dir]
        else:
            directory = [default_dir, xml.get_plugin_directory()]

        # Load the plugins from the default plugin directory.
        manager = PluginManager()
        manager.setPluginPlaces(directory)
        manager.setPluginInfoExtension("plugin")
        manager.collectPlugins()

        # Append tuple with plugin name and enabled=True to the list
        for plugin in manager.getAllPlugins():
            list.append((plugin.name, True))

        return list
def get_plugins():
 
    plugin_analyzer = PluginFileAnalyzerWithInfoFile(name="torrentstausanalyzer", extensions="plugin-manifest")
    plugin_locator = PluginFileLocator(analyzers=[plugin_analyzer])

    extra_plugins_dir = config.getSettingsAsDict()["extra_plugins_dir"]
    plugin_extras = os.path.join(get_config_dir(), extra_plugins_dir)

    directories = [os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")]

    ##
    ## Allow user defined plugins
    ## These plugins should be named as
    ## name.function.{py, plugin-manifest}
    ## Example:
    ## MyPlugin.onstart.py
    ## MyPlguin.onstart.plugin-manifest
    ##
    if os.path.exists(plugin_extras):
        directories.append(plugin_extras)

    manager = PluginManager(directories_list=directories, plugin_locator=plugin_locator)
    manager.collectPlugins()
    plugins = manager.getAllPlugins()

    # Activate all loaded plugins
    for pluginInfo in plugins:
        manager.activatePluginByName(pluginInfo.name)
    return plugins
Exemple #31
0
def main():
    parser = argparse.ArgumentParser(description='Validates file format')
    parser.add_argument('files', nargs='+', help='files to be validated')
    parser.add_argument('--verbose',
                        action='store_true',
                        default=False,
                        help='Shows help about validation')

    args = parser.parse_args()

    simplePluginManager = PluginManager()
    simplePluginManager.setPluginPlaces(["plugins"])
    simplePluginManager.collectPlugins()

    for filename in args.files:
        supported = False
        for plugin in simplePluginManager.getAllPlugins():
            methods = plugin.plugin_object
            if methods.should_manage(filename):
                supported = True
                try:
                    plugin.plugin_object.validate(filename)
                    print('%s sintax ok for %s' % (filename, plugin.name))
                    break
                except Exception as e:
                    print('Invalid file %s for %s' % (filename, plugin.name))
                    if args.verbose:
                        print(e)
        if not supported:
            print('%s cannot be validated' % filename)
class ObfuscatorManager(object):

    def __init__(self):
        # Collect all the obfuscators contained in the ./obfuscators directory. Each obfuscator has an
        # associated *.obfuscator file with some metadata and belongs to a category (see the base class
        # of each obfuscator).
        self.manager = PluginManager(
            directories_list=[os.path.join(os.path.dirname(os.path.realpath(__file__)), 'obfuscators')],
            plugin_info_ext='obfuscator',
            categories_filter={
                'Trivial': obfuscator_category.ITrivialObfuscator,
                'Rename': obfuscator_category.IRenameObfuscator,
                'Encryption': obfuscator_category.IEncryptionObfuscator,
                'Code': obfuscator_category.ICodeObfuscator,
                'Resources': obfuscator_category.IResourcesObfuscator,
                'Other': obfuscator_category.IOtherObfuscator
            }
        )
        self.manager.collectPlugins()

    def get_all_obfuscators(self):
        return self.manager.getAllPlugins()

    def get_obfuscators_names(self):
        return [ob.name for ob in sorted(self.get_all_obfuscators(), key=lambda x: (x.category, x.name))]
Exemple #33
0
    def test_plugins_found(self):
        pm = PluginManager()

        libpath = '%s/OpenMesher/plugins' % (get_python_lib())

        pm.setPluginPlaces([
            '/usr/share/openmesher/plugins',
            '~/.openmesher/plugins',
            './OpenMesher/plugins',
            './plugins',
            libpath,
        ])
        pm.setPluginInfoExtension('plugin')
        pm.setCategoriesFilter({
            'config': IOpenMesherConfigPlugin,
            'package': IOpenMesherPackagePlugin,
            'deploy': IOpenMesherDeployPlugin,
        })
        pm.collectPlugins()
        for plugin in pm.getAllPlugins():
            print('Author: %s' % (plugin.author))
            print('Categories: %s' % (plugin.categories))
            print('Copyright: %s' % (plugin.copyright))
            print('Descr: %s' % (plugin.description))
            print('Error: %s' % (plugin.error))
            print('Name: %s' % (plugin.name))
            print('Path: %s' % (plugin.path))
            print('Version: %s' % (plugin.version))
            print('Website: %s' % (plugin.website))
            print('')
        return True
 def _run_reporting(self, results, objfile):
     #options
     options = dict()
     
     # Build the PluginManager
     reportingPluginManager = PluginManager()
     reportingPluginManager.setPluginPlaces(["reporting"])
     reportingPluginManager.collectPlugins()
     
     # Trigger run from the "Reporting" plugins
     for pluginInfo in reportingPluginManager.getAllPlugins():
         reportingModul = pluginInfo.plugin_object
         reportingModul.set_task(self.task)
         
         # Give it the the relevant reporting.conf section.
         try:
             options = self.cfgReporting.get(pluginInfo.name)
             reportingModul.set_options(options)
         except Exception:
             log.error("Reporting module %s not found in configuration file", pluginInfo.name)  
             
         # If the processing module is disabled in the config, skip it.
         if not options.enabled:
             continue
         
         log.debug("Run Reporting: " + pluginInfo.name)
         
         try:
             # Run the Reporting module
             reportingModul.run(results, objfile)
         except Exception as e:
             log.exception("Failed to run the reporting module \"%s\":",
                           reportingModul.__class__.__name__)
class FurnivallApplication(tornado.web.Application):
	def __init__(self):
		"""
		Sets up the Tornado web server and loads all the init data
		"""

		# Init mongodb database
		self.dbconnection = Connection()
		self.db = self.dbconnection['furnivall']

		# Init plugins
		self.plugin_manager = PluginManager()
		self.plugin_manager.setPluginPlaces(["./plugins"])
		self.plugin_manager.collectPlugins()
		print "Loaded plugins:"
		for plugin_info in self.plugin_manager.getAllPlugins():
			print ' * ' + plugin_info.name

		# Init routes
		urls = [
		] + Route.routes()

		settings = dict(
			static_path = os.path.join(data_dir, "static"),
			template_path = os.path.join(data_dir, "templates"),
			xsrf_cookies = False,
			cookie_secret = "11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1ao/Vo=",
		)
		tornado.web.Application.__init__(self, urls, **settings)
Exemple #36
0
    def load_plugins(self):

        # Build the manager
        simplePluginManager = PluginManager()

        # Tell it the default place(s) where to find plugins
        simplePluginManager.getPluginLocator().updatePluginPlaces(PLUGIN_DIRS)
        # Load all plugins
        simplePluginManager.collectPlugins()

        # Activate all loaded plugins
        for plugin in simplePluginManager.getAllPlugins():
            # print("Importing plugin: %s" % plugin.plugin_object.get_name())

            mnemories = plugin.plugin_object.reportMnemories()
            # print("  Providing: %s" % mnemories)

            for m in mnemories:

                def getKey(mnemory):

                    if mnemory.defaultAlias:
                        return mnemory.defaultAlias

                    return self.key

                # TODO: allow to override aliases by configs?
                self.mnemories[getKey(m)] = m
Exemple #37
0
def group_dashboard(request, group_id):
    # check user is allowed to access this
    user = request.user
    config_installed = 'config' in settings.INSTALLED_APPS
    user_level = user.userprofile.level
    machine_group = get_object_or_404(MachineGroup, pk=group_id)
    business_unit = machine_group.business_unit
    if business_unit not in user.businessunit_set.all():
        if user_level != 'GA':
            return redirect(index)
    if user_level == 'GA' or user_level == 'RW':
        is_editor = True
    else:
        is_editor = False
    machines = machine_group.machine_set.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 = []
    for plugin in manager.getAllPlugins():
        data = {}
        data['name'] = plugin.name
        (data['html'], data['width']) = plugin.plugin_object.show_widget('group_dashboard', machines, machine_group.id)
        output.append(data)
    output = utils.orderPluginOutput(output, 'group_dashboard', machine_group.id)
    c = {'user': request.user, 'machine_group': machine_group, 'user_level': user_level,  'is_editor': is_editor, 'business_unit': business_unit, 'output':output, 'config_installed':config_installed, 'request':request}
    return render_to_response('server/group_dashboard.html', c, context_instance=RequestContext(request))
def run_output_plugins(**kwargs):
  logger = logging.getLogger(__name__)
  logger.info("Begin run_output_plugins")

  simplePluginManager = PluginManager()
  logging.getLogger('yapsy').setLevel(logging.DEBUG)
  simplePluginManager.setCategoriesFilter({
     "OutputResults": output_plugin
     })

  # Tell it the default place(s) where to find plugins
  if logger:
    logger.debug("Plugin directories: %s" % (kwargs['output_plugin_directories']))
  simplePluginManager.setPluginPlaces(kwargs['output_plugin_directories'])

  simplePluginManager.collectPlugins()

  plugin_cnt = 0
  plugin_start_time = time.time()
  for plugin in simplePluginManager.getAllPlugins():
    if logger:
      logger.info("Starting plugin: %s" % (plugin.name))
    if plugin.plugin_object.initialize_plugin(details=plugin.details):
      plugin.plugin_object.emit(prediction_date=kwargs['prediction_date'].astimezone(timezone("US/Eastern")).strftime("%Y-%m-%d %H:%M:%S"),
                                execution_date=kwargs['prediction_run_date'].strftime("%Y-%m-%d %H:%M:%S"),
                                ensemble_tests=kwargs['site_model_ensemble'])
      plugin_cnt += 1
    else:
      logger.error("Failed to initialize plugin: %s" % (plugin.name))
  logger.debug("%d output plugins run in %f seconds" % (plugin_cnt, time.time() - plugin_start_time))
  logger.info("Finished run_output_plugins")
def run_output_plugins(**kwargs):
    logger = logging.getLogger(__name__)
    logger.info("Begin run_output_plugins")

    simplePluginManager = PluginManager()
    logging.getLogger('yapsy').setLevel(logging.DEBUG)
    simplePluginManager.setCategoriesFilter({"OutputResults": output_plugin})

    # Tell it the default place(s) where to find plugins
    if logger:
        logger.debug("Plugin directories: %s" %
                     (kwargs['output_plugin_directories']))
    simplePluginManager.setPluginPlaces(kwargs['output_plugin_directories'])

    simplePluginManager.collectPlugins()

    plugin_cnt = 0
    plugin_start_time = time.time()
    for plugin in simplePluginManager.getAllPlugins():
        if logger:
            logger.info("Starting plugin: %s" % (plugin.name))
        if plugin.plugin_object.initialize_plugin(details=plugin.details):
            plugin.plugin_object.emit(
                prediction_date=kwargs['prediction_date'].astimezone(
                    timezone("US/Eastern")).strftime("%Y-%m-%d %H:%M:%S"),
                execution_date=kwargs['prediction_run_date'].strftime(
                    "%Y-%m-%d %H:%M:%S"),
                ensemble_tests=kwargs['site_model_ensemble'])
            plugin_cnt += 1
        else:
            logger.error("Failed to initialize plugin: %s" % (plugin.name))
    logger.debug("%d output plugins run in %f seconds" %
                 (plugin_cnt, time.time() - plugin_start_time))
    logger.info("Finished run_output_plugins")
 def load_plugins(cls):
     manager = PluginManager()
     manager.setPluginPlaces([os.path.join(os.getcwd(), "plugins/")])
     manager.collectPlugins()
     ret = manager.getAllPlugins()
     logger.info('Loaded {} plugins'.format(len(ret)))
     return ret
Exemple #41
0
def group_dashboard(request, group_id):
    # check user is allowed to access this
    user = request.user
    user_level = user.userprofile.level
    machine_group = get_object_or_404(MachineGroup, pk=group_id)
    business_unit = machine_group.business_unit
    if business_unit not in user.businessunit_set.all():
        if user_level != 'GA':
            return redirect(index)
    if user_level == 'GA' or user_level == 'RW':
        is_editor = True
    else:
        is_editor = False   
    machines = machine_group.machine_set.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 = []
    for plugin in manager.getAllPlugins():
        data = {}
        data['name'] = plugin.name
        (data['html'], data['width']) = plugin.plugin_object.show_widget('group_dashboard', machines, machine_group.id)
        output.append(data)
    output = utils.orderPluginOutput(output, 'group_dashboard', machine_group.id)
    c = {'user': request.user, 'machine_group': machine_group, 'user_level': user_level,  'is_editor': is_editor, 'business_unit': business_unit, 'output':output}
    return render_to_response('server/group_dashboard.html', c, context_instance=RequestContext(request))
Exemple #42
0
    def __init__(self, db, main_config, cwd):
        self.db = db
        self.cnf = main_config

        #The output needs to have the statuses/sizes to ignore and the relevant
        #modules and baseline request
        self.b_cnf = {
            "i_status": [],
            "i_size": [],
            "mods": [],
            "flagsame": False,
            "session": False,
            "force": False,
            "timeout": 0,
        }

        self.multi_Req = []
        self.statuses = []
        self.responses = {}
        self.requests = {}
        self.module = ''  #use the baseline_parse else standard_parse if not

        #Process post plugin modules
        manager = PluginManager()
        manager.setPluginPlaces([cwd + "/modules/post"])
        manager.collectPlugins()
        self.all_plugins = manager.getAllPlugins()
Exemple #43
0
def runCrawler():
	mapURL = {}
	cfgCrawler = Config(os.path.join(RAGPICKER_ROOT, 'config', 'crawler.conf'))	
	
	# Build the PluginManager
	crawlerPluginManager = PluginManager()
	crawlerPluginManager.setPluginPlaces(["crawler"])
	crawlerPluginManager.collectPlugins()
	
	# Trigger run from the "Crawler" plugins
	for pluginInfo in sorted(crawlerPluginManager.getAllPlugins(), key=lambda PluginInfo: PluginInfo.name):
		crawlerModul = pluginInfo.plugin_object
		
		# Config for crawler module
		try:
			options = cfgCrawler.get(pluginInfo.name)
			crawlerModul.set_options(options)
		except Exception:
			log.error("Crawler module %s not found in configuration file", pluginInfo.name)  
			
		# If the crawler module is disabled in the config, skip it.
		if not options.enabled:
			continue
		
		try:
			log.debug("Run Crawler: " + pluginInfo.name)
			returnMap = crawlerModul.run()
			mapURL.update(returnMap)
		except Exception as e:
			log.error('Error (%s) in %s', e, pluginInfo.name)
	
	return mapURL
Exemple #44
0
 def load_plugins(cls):
     manager = PluginManager()
     manager.setPluginPlaces([os.path.join(os.getcwd(), "plugins/")])
     manager.collectPlugins()
     ret = manager.getAllPlugins()
     logger.info('Loaded {} plugins'.format(len(ret)))
     return ret
def runCrawler():
    mapURL = {}
    cfgCrawler = Config(os.path.join(RAGPICKER_ROOT, 'config', 'crawler.conf'))

    # Build the PluginManager
    crawlerPluginManager = PluginManager()
    crawlerPluginManager.setPluginPlaces(["crawler"])
    crawlerPluginManager.collectPlugins()

    # Trigger run from the "Crawler" plugins
    for pluginInfo in sorted(crawlerPluginManager.getAllPlugins(),
                             key=lambda PluginInfo: PluginInfo.name):
        crawlerModul = pluginInfo.plugin_object

        # Config for crawler module
        try:
            options = cfgCrawler.get(pluginInfo.name)
            crawlerModul.set_options(options)
        except Exception:
            log.error("Crawler module %s not found in configuration file",
                      pluginInfo.name)

        # If the crawler module is disabled in the config, skip it.
        if not options.enabled:
            continue

        try:
            log.debug("Run Crawler: " + pluginInfo.name)
            returnMap = crawlerModul.run()
            mapURL.update(returnMap)
        except Exception as e:
            log.error('Error (%s) in %s', e, pluginInfo.name)

    return mapURL
Exemple #46
0
def update_os_families(apps, schema_editor):
    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()
    enabled_plugins = apps.get_model("server", "MachineDetailPlugin")
    for item in enabled_plugins.objects.all():
        default_families = ['Darwin', 'Windows', 'Linux']
        for plugin in manager.getAllPlugins():
            if plugin.name == item.name:

                try:
                    supported_os_families = plugin.plugin_object.supported_os_families(
                    )
                except:
                    supported_os_families = default_families
                item.os_families = utils.flatten_and_sort_list(
                    supported_os_families)
                item.save()
Exemple #47
0
class MarinheiroCmdApp(cmd2.Cmd):
    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()

    @cmd2.options([cmd2.make_option("-c", "--category", action="store",
                                    help="Specify test category.")])
    def do_list(self, arg, opts=None):
        if opts.category:
            categories = self.manager.getPluginsOfCategory(opts.category)
        else:
            categories = self.manager.getAllPlugins()

        for plugin in categories:
            print("{}: {p.name}".format(self.colorize("Name", "bold"), p=plugin))
            print("{}: {p.description}".format(self.colorize("Description", "bold"), p=plugin))
            print()

    @cmd2.options([cmd2.make_option("-c", "--category", action="store",
                                    help="Specify test category.")])
    def do_run(self, arg, opts=None):
        if opts.category:
            categories = self.manager.getPluginsOfCategory(opts.category)
        else:
            categories = self.manager.getAllPlugins()

        for plugin in categories:
            print("{}: {p.name}".format(self.colorize("Name", "bold"), p=plugin))
            print("{}: {p.description}".format(self.colorize("Description", "bold"), p=plugin))
            try:
                output = plugin.plugin_object.run()
            except marinheiro.exceptions.FailedTest as err:
                status = self.colorize("FAILED", "red")
                output = err.msg
            else:
                status = self.colorize("PASSED", "green")
            finally:
                print("{}: {}".format(self.colorize("Status", "bold"), status))
                print("{}: {}".format(self.colorize("Output", "bold"), output))
                print()
class BotInteraction():

    def __init__(self, config):
        self.channel = config['channel']
        self.nickname = config['nickname']
        self.prompt = config['prompt']
        self.parts = ""
        self.ping = ""
        self.username = ""
        self.message = ""
        self.manager = PluginManager()
        self.manager.setPluginPlaces(["plugins"])
        self.manager.collectPlugins()

    def handle_line(self, username, message, parts):
        print(username + ": " + message)

        if self.nickname not in parts[1] and message[0:1] == self.prompt:

            message = message.replace(">", " ").split(None, 1)
            for plugin in self.manager.getAllPlugins():  # Collect all plugins
                try:
                    # Message[0] - search plugin_name
                    plugin_yapsy = self.manager.getPluginByName(message[0])
                    command = []

                    # If the message has arguments - message[1] add to command
                    if len(message) == 2:
                        command = message[1]

                    # To found plugin send arguments.
                    return plugin_yapsy.plugin_object.execute(self.channel,
                                                              username,
                                                              command)
                except:
                    continue

    def check_ping(self, line):
        if line.find("PING") != -1:  # If server pings then pong
            line = string.split(line, " ")
            self.ping = "PONG " + line[1]

        else:
            self.ping = ""
            self.parts = string.split(line, ":")

            if "QUIT" not in self.parts[1] and \
               "JOIN" not in self.parts[1] and \
               "PART" not in self.parts[1]:

                try:
                    # Sets the message variable to the actual message sent
                    self.message = self.parts[2][:len(self.parts[2]) - 1]
                except:
                    self.message = ""
                # Sets the username variable to the actual username
                usernamesplit = string.split(self.parts[1], "!")
                self.username = usernamesplit[0]
Exemple #49
0
def doRun():
    settings = read_config()

    # Load the plugins from the plugin directory.
    manager = PluginManager()
    #TODO: set plugin path to subdir of main script folder.
    manager.setPluginPlaces([PLUGINS_PLACE])
    manager.collectPlugins()
    
    # Loop round the plugins and run discovery.
    for plugin in manager.getAllPlugins():
        plugin.plugin_object.doSetup(settings)
        plugin.plugin_object.doDiscovery()
        
    # Loop round the plugins and print results.
    for plugin in manager.getAllPlugins():
        plugin.plugin_object.doSetup(settings)
        plugin.plugin_object.doOutput()
def main():   
    # Load the plugins from the plugin directory.
    manager = PluginManager(plugin_info_ext='cfg')
    manager.setPluginPlaces(["../plugins"])
    manager.collectPlugins()

    # Loop round the plugins and print their names.
    for plugin in manager.getAllPlugins():
        plugin.plugin_object.print_name()
Exemple #51
0
def index(request):
    # Get the current user's Business Units
    user = request.user
    # Count the number of users. If there is only one, they need to be made a GA
    if User.objects.count() == 1:
        # The first user created by syncdb won't have a profile. If there isn't one, make sure they get one.
        try:
            profile = UserProfile.objects.get(user=user)
        except UserProfile.DoesNotExist:
            profile = UserProfile(user=user)

        profile.level = "GA"
        profile.save()
    user_level = user.userprofile.level
    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)
    if user_level != "GA":
        # user has many BU's display them all in a friendly manner
        business_units = user.businessunit_set.all()
        if user.businessunit_set.count() == 1:
            # user only has one BU, redirect to it
            for bu in user.businessunit_set.all():
                return redirect("server.views.bu_dashboard", bu_id=bu.id)
                break
    else:
        machines = Machine.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 = []
        # 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("front", machines)
            # output.append(plugin.plugin_object.show_widget('front'))
            output.append(data)
        output = utils.orderPluginOutput(output)

        # get the user level - if they're a global admin, show all of the machines. If not, show only the machines they have access to
        business_units = BusinessUnit.objects.all()
        config_installed = "config" in settings.INSTALLED_APPS

        c = {
            "user": request.user,
            "business_units": business_units,
            "output": output,
            "config_installed": config_installed,
        }
        return render_to_response("server/index.html", c, context_instance=RequestContext(request))
Exemple #52
0
def main():
    # Create plugin manager
    manager = PluginManager()
    manager.setPluginPlaces([PluginFolder])
    # Collect plugins
    manager.collectPlugins()

    for plugin in manager.getAllPlugins():
        plugin.plugin_object.say_hello()
    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
Exemple #54
0
def main():
    """docstring for main"""
    # Load the plugins from the plugin directory.
    manager = PluginManager()
    manager.setPluginPlaces(["plugins"])
    manager.collectPlugins()

    # Loop round the plugins executing them.
    for plugin in manager.getAllPlugins():
        plugin.plugin_object.run()
Exemple #55
0
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 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()
Exemple #57
0
class ProcessingManager(object):
    def __init__(self):
        self.plugin_location = [PROCESSING_MODULE_DIR]
        self.pluginManager = PluginManager(plugin_info_ext="plugin")
        self.pluginManager.setPluginPlaces(self.plugin_location)
        self.pluginManager.collectPlugins()

    def modules_info(self):
        """
        Get information with regards to each modules loaded. It includes author,category, copyright, description,
        details, name, version and website.
        :return: information of all modules loaded
        """
        modules_info = {}
        for pluginInfo in self.pluginManager.getAllPlugins():
            modules_info[pluginInfo.name] = pluginInfo

        return modules_info

    def run(self,session_id):
        results = {}
        for plugInfo in self.pluginManager.getAllPlugins():
            result = plugInfo.plugin_object.run(session_id)
            #format int json
            result_json = json.dumps(result, sort_keys=True, indent=4)
            #save into session
            module_name = plugInfo.name

            results[module_name] = result_json

        return results


    def general_information(self, session_id):
        """
        Get general information of the session
        :param session_id:
        :return: dict
        """
        plugin = self.pluginManager.getPluginByName(name="general_information")
        result = plugin.plugin_object.run(session_id)

        return result
Exemple #58
0
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()