Esempio n. 1
0
    def __init__(self, path, args=None, library_path=None):
        """
		:param tuple path: A tuple of directories from which to load plugins.
		:param tuple args: Arguments which should be passed to plugins when
			their class is initialized.
		:param str library_path: A path to use for plugins library dependencies.
			This value will be added to :py:attr:`sys.path` if it is not already
			included.
		"""
        self._lock = threading.RLock()
        self.plugin_init_args = (args or ())
        self.plugin_base = pluginbase.PluginBase(
            package='king_phisher.plugins.loaded')
        self.plugin_source = self.plugin_base.make_plugin_source(
            searchpath=path)
        self.loaded_plugins = {}
        """A dictionary of the loaded plugins and their respective modules."""
        self.enabled_plugins = {}
        """A dictionary of the enabled plugins and their respective instances."""
        self.logger = logging.getLogger('KingPhisher.Plugins.Manager')

        library_path = library_path or _resolve_lib_path()
        if library_path is None:
            self.logger.warning(
                'unable to resolve a valid library path for plugin dependencies'
            )
        else:
            if library_path not in sys.path:
                sys.path.append(library_path)
            library_path = os.path.abspath(library_path)
            self.logger.debug('plugin dependency path: ' + library_path)
        self.library_path = library_path
        """
Esempio n. 2
0
def run(game_dir, setup_only):
    """Run the game to completion or ctrl-c, saving checkpoints regularly."""

    # Get Mailgun key.
    mailgun_key_path = os.path.expanduser(
        "~/.config/godfather/mailgun_key.txt")
    logging.info("Checking for %s..." % mailgun_key_path)
    if (os.path.isfile(mailgun_key_path)):
        logging.info("Loading %s..." % mailgun_key_path)
        mailgun_key = open(mailgun_key_path).read().strip()
    else:
        raise click.ClickException("Must create %s." % mailgun_key_path)

    # Create backup directory if it doesn't exist.
    backup_dir = os.path.join(game_dir, "backups")
    logging.info("Creating %s..." % backup_dir)
    os.makedirs(backup_dir, exist_ok=True)

    # Create game.pickle if it doesn't exist.
    setup_path = os.path.join(game_dir, "setup.py")
    game_path = os.path.join(game_dir, "game.pickle")
    logging.info("Checking for %s..." % game_path)
    if os.path.isfile(game_path):
        logging.info("%s already exists." % game_path)
    else:
        logging.info("Loading %s..." % setup_path)
        plugin_base = pluginbase.PluginBase(package="plugins")
        plugin_source = plugin_base.make_plugin_source(searchpath=[game_dir])
        setup = plugin_source.load_plugin("setup")
        if not isinstance(setup.game, mafia.Game):
            raise click.ClickException(
                "'game' in %s is not a mafia.Game object." % setup_path)

        logging.info("Creating %s..." % game_path)
        moderator = Moderator(path=game_path,
                              game=setup.game,
                              game_name=setup.game_name,
                              moderator_name=setup.moderator_name,
                              domain=setup.domain,
                              public_cc=setup.public_cc,
                              private_cc=setup.private_cc,
                              time_zone=setup.time_zone,
                              night_end=setup.night_end,
                              day_end=setup.day_end,
                              mailgun_key=mailgun_key)
        pickle.dump(moderator, open(game_path, "wb"))

    # Load the moderator.
    moderator = load_game(game_path)

    if setup_only:
        return

    # Start the server.
    server = Server(moderator)
    server_thread = threading.Thread(target=server.run, daemon=True)
    server_thread.start()

    # Run the Moderator (runs until interrupted).
    moderator.run()
Esempio n. 3
0
 def __init__(self, frmwk, searchpath):
     self.logger = logging.getLogger('termineter.module_manager')
     self.frmwk = frmwk
     self.source = pluginbase.PluginBase(
         package='termineter.modules').make_plugin_source(
             searchpath=searchpath)
     self._modules = {}
     for module_id in self.source.list_plugins():
         self._init_pymodule(self.source.load_plugin(module_id))
Esempio n. 4
0
    def test_setup_py(self):
        """'init' should create a valid setup.py."""
        exec_godfather(["init"])

        plugin_base = pluginbase.PluginBase(package="plugins")
        plugin_source = plugin_base.make_plugin_source(searchpath=["."])
        setup = plugin_source.load_plugin("setup")
        assert isinstance(setup.game, mafia.Game)
        assert isinstance(setup.night_end, datetime.time)
        assert isinstance(setup.day_end, datetime.time)
Esempio n. 5
0
  def test_setup_py(self):
    """'init' should create a valid setup.py."""
    setup_path = os.path.join(self.game_dir, "setup.py")
    game_path = os.path.join(self.game_dir, "game.pickle")

    exec_godfather(["init", self.game_dir])

    plugin_base = pluginbase.PluginBase(package="plugins")
    plugin_source = plugin_base.make_plugin_source(searchpath=[self.game_dir])
    setup = plugin_source.load_plugin("setup")
    assert isinstance(setup.game, mafia.Game)
    assert isinstance(setup.night_end, datetime.time)
    assert isinstance(setup.day_end, datetime.time)
Esempio n. 6
0
	def __init__(self, path, args=None):
		"""
		:param tuple path: A tuple of directories from which to load plugins.
		:param tuple args: Arguments which should be passed to plugins when their class is initialized.
		"""
		self._lock = threading.RLock()
		self.plugin_init_args = (args or ())
		self.plugin_base = pluginbase.PluginBase(package='king_phisher.plugins.loaded')
		self.plugin_source = self.plugin_base.make_plugin_source(searchpath=path)
		self.loaded_plugins = {}
		"""A dictionary of the loaded plugins and their respective modules."""
		self.enabled_plugins = {}
		"""A dictionary of the enabled plugins and their respective instances."""
		self.logger = logging.getLogger('KingPhisher.Plugins.Manager')
Esempio n. 7
0
    def __init__(self, searchpath=None):
        searchpath = searchpath or []
        searchpath.append(get_path('plugins'))

        self.source = pluginbase.PluginBase(
            package='protocon.plugins').make_plugin_source(
                searchpath=searchpath)
        self.connection_drivers = {}
        self.transcoders = {}
        for plugin in self.source.list_plugins():
            module = self.source.load_plugin(plugin)
            if hasattr(module, 'ConnectionDriver'):
                self.connection_drivers[plugin] = module.ConnectionDriver
            if hasattr(module, 'Transcoder'):
                self.transcoders[plugin] = module.Transcoder
Esempio n. 8
0
def run_game(setup_only=False, resolve_one_phase=False):
    # Create backup directory if it doesn't exist.
    logging.info("Creating %s..." % BACKUP_PATH)
    os.makedirs(BACKUP_PATH, exist_ok=True)

    # Create game.pickle if it doesn't exist.
    logging.info("Checking for %s..." % GAME_PATH)
    if os.path.isfile(GAME_PATH):
        logging.info("%s already exists." % GAME_PATH)
    else:
        logging.info("Loading %s..." % SETUP_PATH)
        plugin_base = pluginbase.PluginBase(package="plugins")
        plugin_source = plugin_base.make_plugin_source(searchpath=["."])
        setup = plugin_source.load_plugin("setup")
        if not isinstance(setup.game, mafia.Game):
            raise click.ClickException(
                "'game' in %s is not a mafia.Game object." % SETUP_PATH)

        logging.info("Creating %s..." % GAME_PATH)
        moderator = Moderator(path=GAME_PATH,
                              game=setup.game,
                              game_name=setup.game_name,
                              time_zone=setup.time_zone,
                              night_end=setup.night_end,
                              day_end=setup.day_end,
                              forum=setup.forum)
        pickle.dump(moderator, open(GAME_PATH, "wb"))

    # Load the moderator.
    moderator = load_game(GAME_PATH)

    if setup_only:
        return

    if resolve_one_phase:
        # Resolve the next phase and exit.
        moderator.phase_end = datetime.datetime.now(
            moderator.time_zone) - moderator.forum.receipt_lag
        set_cancelled(True)
    else:
        # Start the server.
        server = Server(moderator)
        server_thread = threading.Thread(target=server.run, daemon=True)
        server_thread.start()

    # Run the Moderator (runs until interrupted).
    moderator.run()
Esempio n. 9
0
def runAll(options=None):
    '''
    Runs all the plugins at once
    '''
    log = logging.getLogger('runAll')
    log.debug('Loading all modules')
    plugin = pluginbase.PluginBase(package='modules')
    pluginsource = plugin.make_plugin_source(searchpath=[
        './modules/application', './modules/backcomp', './modules/invalid',
        './modules/parser', './modules/transaction'
    ])
    if options is not None and options.build_cache:
        print('executing')
        buildcache(pluginsource)  # <- Uncomment this line to build cache
        return
    for plug in pluginsource.list_plugins():
        p = pluginsource.load_plugin(plug)
        p.run()
Esempio n. 10
0
    def __init__(self):
        """
    Apps class.

    """

        # Setup app system
        self.plugin_base = pluginbase.PluginBase(package='opsoro.apps')
        self.plugin_source = self.plugin_base.make_plugin_source(
            searchpath=[get_path('.')])

        self.apps = {}
        self.active_apps = []
        self.background_apps = []

        # Make sure apps are only registered during setup
        self.apps_can_register_bp = True
        self.current_bp_app = ""  # Keep track of current app for blueprint setup

        Users.app_change_handler = self.refresh_active
Esempio n. 11
0
def cli(context, pkg_path, configfiles, debug, confvars, debug_ssh):
    pkg_path = list(pkg_path)
    if 'REMAND_PKG_PATH' in os.environ:
        pkg_path.extend(os.environ['REMAND_PKG_PATH'].split(os.pathsep))

    # add contrib to pkg path
    import remand.contrib as contrib
    pkg_path.append(os.path.abspath(os.path.dirname(contrib.__file__)))

    # pluginbase is imported here because just importing it breaks Crypto
    # (and with it paramiko)
    import pluginbase
    plugin_base = pluginbase.PluginBase(package='remand.ext')

    obj = context.obj = {}
    handler = ColorizedStderrHandler(
        level=logbook.DEBUG if debug else logbook.INFO)

    # setup logging
    logbook.compat.redirect_logging()
    handler.push_application()

    if not debug_ssh:
        logbook.NullHandler(filter=lambda r, h: r.channel.startswith(
            'paramiko')).push_application()

    # read configuration and host registry
    obj['config'] = load_configuration(APP_NAME, configfiles)

    # set configuration values
    for k, v in confvars:
        obj['config']['Match:.*'][k] = v
        log.debug('Set Match.*:[{!r}] = {!r}'.format(k, v))

    obj['hosts'] = HostRegistry(obj['config'])

    plugin_source = plugin_base.make_plugin_source(searchpath=list(pkg_path) +
                                                   ['.'])
    obj['plugin_source'] = plugin_source
Esempio n. 12
0
    def load_plugins(self):
        self.logger.debug('Loading plugins from folder')

        plugin_base = pluginbase.PluginBase(package='aleph.plugins',
                                            searchpath=[get_path('plugins')])
        self.plugin_source = plugin_base.make_plugin_source(
            searchpath=[get_path('plugins')])

        for plugin_name in self.plugin_source.list_plugins():
            plugin = self.plugin_source.load_plugin(plugin_name)
            self.plugins.append(plugin.setup(self.sample_queue))
            self.logger.debug('Plugin "%s" loaded' % plugin_name)

        runs = 0
        max_runs = 30  # Max recursion runs before considering circular reference

        while (runs <= max_runs):
            rc = self.sort_plugins()
            if rc == 0: break
            runs += 1

        if runs == max_runs:
            self.logger.error('Possible circular reference in plugin chain')
Esempio n. 13
0
    def __init__(self):
        self.request_handler = RHandler(self)

        # Create flask instance for webserver
        self.flaskapp = Flask(__name__)

        self.flaskapp.config.from_pyfile('settings.cfg')
        self.babel = Babel(self.flaskapp)

        # Setup key for sessions
        self.flaskapp.secret_key = "5\x075y\xfe$\x1aV\x1c<A\xf4\xc1\xcfst0\xa49\x9e@\x0b\xb2\x17"

        # Setup login manager
        self.login_manager = LoginManager()
        self.login_manager.init_app(self.flaskapp)
        self.login_manager.login_view = "login"
        self.setup_user_loader()

        # Variable to keep track of the active user
        self.active_session_key = None

        # Token to authenticate socket connections
        # Client requests token via AJAX, server generates token if session is valid
        # Client then sends the token to the server via SockJS, validating the connection
        self.sockjs_token = None

        # Setup app system
        self.plugin_base = pluginbase.PluginBase(package="opsoro.server.apps")
        self.plugin_source = self.plugin_base.make_plugin_source(
            searchpath=[get_path("./../apps")])

        self.apps = {}
        self.activeapp = None
        self.apps_can_register_bp = True  # Make sure apps are only registered during setup
        self.current_bp_app = ""  # Keep track of current app for blueprint setup

        # Socket callback dicts
        self.sockjs_connect_cb = {}
        self.sockjs_disconnect_cb = {}
        self.sockjs_message_cb = {}

        # if Preferences.check_if_update():
        #     print_info("Update available")
        #     Preferences.update()

        for plugin_name in self.plugin_source.list_plugins():
            self.current_bp_app = plugin_name

            plugin = self.plugin_source.load_plugin(plugin_name)
            print_apploaded(plugin_name)

            if not hasattr(plugin, "config"):
                plugin.config = {"full_name": "No name",
                                 "icon": "fa-warning",
                                 'color': '#333'}

            if "full_name" not in plugin.config:
                plugin.config["full_name"] = "No name"

            if "icon" not in plugin.config:
                plugin.config["icon"] = "fa-warning"

            self.apps[plugin_name] = plugin
            try:
                plugin.setup(self)
            except AttributeError:
                print_info("%s has no setup function" % plugin_name)

            try:
                plugin.setup_pages(self)
            except AttributeError:
                print_info("%s has no setup_pages function" % plugin_name)

        self.current_bp_app = ""
        self.apps_can_register_bp = False

        # Initialize all URLs
        self.request_handler.set_urls()

        # Run stop function at exit
        atexit.register(self.at_exit)
Esempio n. 14
0
import pluginbase

import argparse
import json
import os
import sys

plugin_base = pluginbase.PluginBase(package="koinos_codegen.plugins")
# TODO:  search path for builtin plugins?


class Application:
    def __init__(self, name="koinos_codegen", plugin_searchpath=[]):
        self.name = name
        self.targets = {}
        self.plugin_source = plugin_base.make_plugin_source(
            searchpath=plugin_searchpath,
            identifier=self.name,
        )
        for plugin_name in self.plugin_source.list_plugins():
            plugin = self.plugin_source.load_plugin(plugin_name)
            plugin.setup(self)

    def register_target(self, name, target):
        self.targets[name] = target


class ApplicationError(Exception):
    pass