Beispiel #1
0
def run(config=None):
    if config:
        config = b3.getAbsolutePath(config)
    else:
        # search for the config file
        config = None
        for p in (
            "b3.xml",
            "conf/b3.xml",
            "b3/conf/b3.xml",
            "~/b3.xml",
            "~/conf/b3.xml",
            "~/b3/conf/b3.xml",
            "@b3/conf/b3.xml",
        ):
            path = b3.getAbsolutePath(p)
            print "Searching for config file: %s" % path
            if os.path.isfile(path):
                config = path
                break

    if not config:
        Setup(config)
        # raise SystemExit('Could not find config file.')

    b3.start(config)
Beispiel #2
0
    def __init__(self, config=None):
        """
        Object constructor.
        :param config: The B3 configuration file path
        """
        if config:
            # use the specified configuration file
            config = b3.getAbsolutePath(config, True)
            if not os.path.isfile(config):
                console_exit('ERROR: configuration file not found (%s).\n'
                             'Please visit %s to create one.' % (config, B3_CONFIG_GENERATOR))
        else:
            # search a configuration file
            for p in ('b3.%s', 'conf/b3.%s', 'b3/conf/b3.%s',
                      os.path.join(HOMEDIR, 'b3.%s'), os.path.join(HOMEDIR, 'conf', 'b3.%s'),
                      os.path.join(HOMEDIR, 'b3', 'conf', 'b3.%s'), '@b3/conf/b3.%s'):
                for e in ('ini', 'cfg', 'xml'):
                    path = b3.getAbsolutePath(p % e, True)
                    if os.path.isfile(path):
                        print "Using configuration file: %s" % path
                        config = path
                        sleep(3)
                        break

            if not config:
                console_exit('ERROR: could not find any valid configuration file.\n'
                             'Please visit %s to create one.' % B3_CONFIG_GENERATOR)
        try:
            self.config = b3.config.MainConfig(b3.config.load(config))
            if self.config.analyze():
                raise b3.config.ConfigFileNotValid
        except b3.config.ConfigFileNotValid:
            console_exit('ERROR: configuration file not valid (%s).\n'
                         'Please visit %s to generate a new one.' % (config, B3_CONFIG_GENERATOR))
Beispiel #3
0
def run_console(options):
    """
    Run B3 in console mode.
    :param options: command line options
    """
    analysis = None     # main config analysis result
    printexit = False   # whether the exit message has been printed alreadty or not

    try:

        if options.config:
            config = b3.getAbsolutePath(options.config, True)
            if not os.path.isfile(config):
                printexit = True
                console_exit('ERROR: configuration file not found (%s).\n'
                             'Please visit %s to create one.' % (config, B3_CONFIG_GENERATOR))
        else:
            config = None
            for p in ('b3.%s', 'conf/b3.%s', 'b3/conf/b3.%s',
                      os.path.join(HOMEDIR, 'b3.%s'), os.path.join(HOMEDIR, 'conf', 'b3.%s'),
                      os.path.join(HOMEDIR, 'b3', 'conf', 'b3.%s'), '@b3/conf/b3.%s'):
                for e in ('ini', 'cfg', 'xml'):
                    path = b3.getAbsolutePath(p % e, True)
                    if os.path.isfile(path):
                        print "Using configuration file: %s" % path
                        config = path
                        sleep(3)
                        break

            if not config:
                printexit = True
                console_exit('ERROR: could not find any valid configuration file.\n'
                             'Please visit %s to create one.' % B3_CONFIG_GENERATOR)

        # LOADING MAIN CONFIGURATION
        main_config = b3.config.MainConfig(b3.config.load(config))
        analysis = main_config.analyze()
        if analysis:
            raise b3.config.ConfigFileNotValid('invalid configuration file specified')

        # START B3
        b3.start(main_config, options)

    except b3.config.ConfigFileNotValid:
        if analysis:
            print 'CRITICAL: invalid configuration file specified:\n'
            for problem in analysis:
                print"  >>> %s\n" % problem
        else:
            print 'CRITICAL: invalid configuration file specified!'
        raise SystemExit(1)
    except SystemExit, msg:
        if not printexit and main_is_frozen():
            if sys.stdout != sys.__stdout__:
                sys.stdout = sys.__stdout__
                sys.stderr = sys.__stderr__
            print msg
            raw_input("press any key to continue...")
        raise
Beispiel #4
0
def run(options):
    """
    Run B3 in console.
    :param options: command line options
    """
    analysis = None     # main config analysis result
    printexit = False   # whether the exit message has been printed alreadty or not

    try:

        if options.config:
            config = b3.getAbsolutePath(options.config, True)
            if not os.path.isfile(config):
                printexit = True
                console_exit('ERROR: configuration file not found (%s).\n'
                             'Please visit %s to create one.' % (config, B3_CONFIG_GENERATOR))
        else:
            config = None
            for p in ('b3.%s', 'conf/b3.%s', 'b3/conf/b3.%s',
                      os.path.join(HOMEDIR, 'b3.%s'), os.path.join(HOMEDIR, 'conf', 'b3.%s'),
                      os.path.join(HOMEDIR, 'b3', 'conf', 'b3.%s'), '@b3/conf/b3.%s'):
                for e in ('ini', 'cfg', 'xml'):
                    path = b3.getAbsolutePath(p % e, True)
                    if os.path.isfile(path):
                        print "Using configuration file: %s" % path
                        config = path
                        sleep(3)
                        break

            if not config:
                printexit = True
                console_exit('ERROR: could not find any valid configuration file.\n'
                             'Please visit %s to create one.' % B3_CONFIG_GENERATOR)

        # LOADING MAIN CONFIGURATION
        main_config = b3.config.MainConfig(b3.config.load(config))
        analysis = main_config.analyze()
        if analysis:
            raise b3.config.ConfigFileNotValid('invalid configuration file specified')

        # START B3
        b3.start(main_config, options)

    except b3.config.ConfigFileNotValid:
        if analysis:
            print 'CRITICAL: invalid configuration file specified:\n'
            for problem in analysis:
                print"  >>> %s\n" % problem
        else:
            print 'CRITICAL: invalid configuration file specified!'
        raise SystemExit(1)
    except SystemExit, msg:
        if not printexit and main_is_frozen():
            if sys.stdout != sys.__stdout__:
                sys.stdout = sys.__stdout__
                sys.stderr = sys.__stderr__
            print msg
            raw_input("press any key to continue...")
        raise
 def init(self, config_content=None):
     """ load plugin config and initialise the plugin """
     if config_content:
         self.conf.loadFromString(config_content)
     else:
         if os.path.isfile(b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini')):
             self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini'))
         else:
             raise unittest.SkipTest("default config file '%s' does not exists" % b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini'))
     self.p.onLoadConfig()
     self.p.onStartup()
 def test_nominal(self):
     # GIVEN
     existing_file_path = b3.getAbsolutePath('/a/file/that/exists')
     when(os.path).isfile(existing_file_path).thenReturn(True)
     self.conf.loadFromString(dedent(r"""
         [settings]
         private_key_file: /a/file/that/exists
     """))
     # WHEN
     self.p.onLoadConfig()
     # THEN
     self.assertIsNotNone(self.p.private_key_file)
     self.assertEqual(existing_file_path, b3.getAbsolutePath(self.p.private_key_file))
Beispiel #7
0
 def init(self, config_content=None):
     """ load plugin config and initialise the plugin """
     if config_content:
         self.conf.loadFromString(config_content)
     else:
         if os.path.isfile(
                 b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini')):
             self.conf.load(
                 b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini'))
         else:
             raise unittest.SkipTest(
                 "default config file '%s' does not exists" %
                 b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini'))
     self.p.onLoadConfig()
     self.p.onStartup()
Beispiel #8
0
    def onStartup(self):
        """
        Initialize plugin settings.
        """
        self._adminPlugin = self.console.getPlugin('admin')

        # patch the admin module
        patch_admin_module(self._adminPlugin)

        # create database tables (if needed)
        if 'cmdgrants' not in self.console.storage.getTables():
            sql_path_main = b3.getAbsolutePath('@b3/plugins/cmdmanager/sql')
            sql_path = os.path.join(sql_path_main, self.console.storage.dsnDict['protocol'], 'cmdmanager.sql')
            self.console.storage.queryFromFile(sql_path)

        # register our commands
        if 'commands' in self.config.sections():
            for cmd in self.config.options('commands'):
                level = self.config.get('commands', cmd)
                sp = cmd.split('-')
                alias = None
                if len(sp) == 2:
                    cmd, alias = sp

                func = getCmd(self, cmd)
                if func:
                    self._adminPlugin.registerCommand(self, cmd, level, func, alias)

        # register events needed
        self.registerEvent('EVT_CLIENT_AUTH', self.onAuth)

        # notice plugin started
        self.debug('plugin started')
    def onStartup(self):
        """
        Initialize plugin settings
        """
        self.adminPlugin = self.console.getPlugin('admin')
        if not self.adminPlugin:
            raise AttributeError('could not find admin plugin')

        # create database tables (if needed)
        if 'nicks' not in self.console.storage.getTables():
            sql_path_main = b3.getAbsolutePath('@b3/plugins/nickreg/sql')
            sql_path = os.path.join(sql_path_main,
                                    self.console.storage.dsnDict['protocol'],
                                    'nickreg.sql')
            self.console.storage.queryFromFile(sql_path)

        # register our commands
        self.adminPlugin.registerCommand(self, 'registernick', self.min_level,
                                         self.cmd_regnick, 'regnick')
        self.adminPlugin.registerCommand(self, 'deletenick', self.min_level,
                                         self.cmd_delnick, 'delnick')
        self.adminPlugin.registerCommand(self, 'listnick', self.min_level,
                                         self.cmd_listnick)

        # register our events
        self.registerEvent('EVT_CLIENT_NAME_CHANGE',
                           self.on_client_name_change)
        self.registerEvent('EVT_GAME_MAP_CHANGE', self.on_map_change)

        # install crontab
        self.crontab = b3.cron.PluginCronTab(self, self.execute_crontab,
                                             '*/%s' % self.interval)
        self.console.cron + self.crontab
Beispiel #10
0
    def connect(self):
        """
        Establish and return a connection with the storage layer.
        Will store the connection object also in the 'db' attribute so in the future we can reuse it.
        :return The connection instance if established successfully, otherwise None.
        """
        try:
            import sqlite3
            path = b3.getWritableFilePath(self.dsn[9:])
            self.console.bot("Using database file: %s" % path)
            is_new_database = not os.path.isfile(path)
            self.db = sqlite3.connect(path, check_same_thread=False)
            self.db.isolation_level = None  # set autocommit mode
        except Exception as e:
            self.db = None
            self.console.error('Database connection failed: %s', e)
            if self._consoleNotice:
                self.console.screen.write('Connecting to DB : FAILED\n')
                self._consoleNotice = False
        else:
            # import SQL script if necessary
            if path == ':memory:' or is_new_database:
                self.console.info("Importing SQL file: %s..." %
                                  b3.getAbsolutePath("@b3/sql/sqlite/b3.sql"))
                self.queryFromFile("@b3/sql/sqlite/b3.sql")

            if self._consoleNotice:
                self.console.screen.write('Connecting to DB : OK\n')
                self._consoleNotice = False
        finally:
            return self.db
Beispiel #11
0
    def setUp(self):
        SpamcontrolTestCase.setUp(self)

        with open(b3.getAbsolutePath(
                '@b3/conf/plugin_spamcontrol.ini')) as default_conf:
            self.init_plugin(default_conf.read())

        self.joe = FakeClient(self.console,
                              name="Joe",
                              exactName="Joe",
                              guid="zaerezarezar",
                              groupBits=1)
        self.joe.connects("1")

        # let's say our game has a new event : EVT_CLIENT_RADIO
        EVT_CLIENT_RADIO = self.console.Events.createEvent(
            'EVT_CLIENT_RADIO', 'Event client radio')

        # teach the Spamcontrol plugin how to react on such events
        def onRadio(this, event):
            new_event = Event(type=event.type,
                              client=event.client,
                              target=event.target,
                              data=event.data['text'])
            this.onChat(new_event)

        self.p.onRadio = new.instancemethod(onRadio, self.p, SpamcontrolPlugin)
        self.p.registerEvent('EVT_CLIENT_RADIO', self.p.onRadio)

        # patch joe to make him able to send radio messages
        def radios(me, text):
            me.console.queueEvent(
                Event(type=EVT_CLIENT_RADIO, client=me, data={'text': text}))

        self.joe.radios = new.instancemethod(radios, self.joe, FakeClient)
    def onStartup(self):
        """
        Initialize plugin settings.
        """
        self._adminPlugin = self.console.getPlugin('admin')

        # patch the admin module
        patch_admin_module(self._adminPlugin)

        # create database tables (if needed)
        if 'cmdgrants' not in self.console.storage.getTables():
            sql_path_main = b3.getAbsolutePath('@b3/plugins/cmdmanager/sql')
            sql_path = os.path.join(sql_path_main, self.console.storage.dsnDict['protocol'], 'cmdmanager.sql')
            self.console.storage.queryFromFile(sql_path)

        # register our commands
        if 'commands' in self.config.sections():
            for cmd in self.config.options('commands'):
                level = self.config.get('commands', cmd)
                sp = cmd.split('-')
                alias = None
                if len(sp) == 2:
                    cmd, alias = sp

                func = getCmd(self, cmd)
                if func:
                    self._adminPlugin.registerCommand(self, cmd, level, func, alias)

        # register events needed
        self.registerEvent('EVT_CLIENT_AUTH', self.onAuth)

        # notice plugin started
        self.debug('plugin started')
Beispiel #13
0
    def queryFromFile(self, fp, silent=False):
        """
        This method executes an external sql file on the current database.
        :param fp: The filepath of the file containing the SQL statements.
        :param silent: Whether or not to silence MySQL warnings.
        :raise Exception: If the query cannot be evaluated or if the given path cannot be resolved.
        """
        # use existing connection or create a new one
        # duplicate code of query() method which is needed not to spam the database
        # with useless connection attempts (one for each query in the SQL file)
        connection = self.getConnection()
        if not connection:
            raise Exception(
                'lost connection with the storage layer during query')

        # save standard error output
        orig_stderr = sys.stderr
        if silent:
            # silence mysql warnings and such
            sys.stderr = open(os.devnull, 'w')

        path = b3.getAbsolutePath(fp)
        if not os.path.exists(path):
            raise Exception('SQL file does not exist: %s' % path)

        with open(path, 'r') as sqlfile:
            statements = self.getQueriesFromFile(sqlfile)

        for stmt in statements:
            # will stop if a single query generate an exception
            self.query(stmt)

        # reset standard error output
        sys.stderr = orig_stderr
Beispiel #14
0
 def getpath(self, section, setting):
     """
     Return an absolute path name and expand the user prefix (~).
     :param section: The configuration file section.
     :param setting: The configuration file setting.
     """
     return b3.getAbsolutePath(self.get(section, setting), decode=True)
Beispiel #15
0
    def test_no_generic_or_default_warn_reason(self):

        # load the default plugin_admin.ini file after having remove the 'generic' setting from section 'warn_reasons'
        new_config_content = ""
        with open(b3.getAbsolutePath('@b3/conf/plugin_admin.ini')) as config_file:
            is_in_warn_reasons_section = False
            for line in config_file:
                if line == '[warn_reasons]':
                    is_in_warn_reasons_section = True
                if not is_in_warn_reasons_section:
                    new_config_content += (line + '\n')
                else:
                    if line.startswith('['):
                        new_config_content += (line + '\n')
                        is_in_warn_reasons_section = False
                    else:
                        if line.startswith("generic") or line.startswith("default"):
                            pass
                        else:
                            new_config_content += (line + '\n')
        self.init(new_config_content)

        self.joe.message = Mock(lambda x: sys.stdout.write("message to Joe: " + x + "\n"))
        self.joe.connects(0)
        self.joe.says('!warntest')
        self.joe.message.assert_called_once_with('^2TEST: ^1WARNING^7 [^31^7]: ^7behave yourself')
        self.joe.message.reset_mock()
        self.joe.says('!warntest argue')
        self.joe.message.assert_called_once_with('^2TEST: ^1WARNING^7 [^31^7]: ^3Rule #3: No arguing with admins (listen and learn or leave)')
Beispiel #16
0
    def setUp(self):

        B3TestCase.setUp(self)
        self.console.gameName = 'f00'

        self.adminPlugin = AdminPlugin(self.console,
                                       '@b3/conf/plugin_admin.ini')
        when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        self.conf = CfgConfigParser()
        self.conf.loadFromString(
            dedent(r"""
            [commands]
            plugin: superadmin
        """))

        self.p = PluginmanagerPlugin(self.console, self.conf)
        when(self.console).getPlugin("pluginmanager").thenReturn(
            self.adminPlugin)
        self.p.onLoadConfig()
        self.p.onStartup()

        when(self.console.config).get_external_plugins_dir().thenReturn(
            b3.getAbsolutePath('@b3\\extplugins'))

        # store them also in the console _plugins dict
        self.console._plugins['admin'] = self.adminPlugin
        self.console._plugins['pluginmanager'] = self.p
 def test_default_conf(self):
     with open(b3.getAbsolutePath(
             '@b3/conf/plugin_spamcontrol.ini')) as default_conf:
         self.init_plugin(default_conf.read())
     self.assertEqual(self.default_max_spamins, self.p._maxSpamins)
     self.assertEqual(self.default_mod_level, self.p._modLevel)
     self.assertEqual(self.default_falloff_rate, self.p._falloffRate)
    def onStartup(self):
        """
        Initialize plugin settings
        """
        self.adminPlugin = self.console.getPlugin('admin')
        if not self.adminPlugin:
            raise AttributeError('could not find admin plugin')

        # create database tables (if needed)
        if 'nicks' not in self.console.storage.getTables():
            sql_path_main = b3.getAbsolutePath('@b3/plugins/nickreg/sql')
            sql_path = os.path.join(sql_path_main, self.console.storage.dsnDict['protocol'], 'nickreg.sql')
            self.console.storage.queryFromFile(sql_path)

        # register our commands
        self.adminPlugin.registerCommand(self, 'registernick', self.min_level, self.cmd_regnick,  'regnick')
        self.adminPlugin.registerCommand(self, 'deletenick', self.min_level, self.cmd_delnick,  'delnick')
        self.adminPlugin.registerCommand(self, 'listnick', self.min_level, self.cmd_listnick)

        # register our events
        self.registerEvent('EVT_CLIENT_NAME_CHANGE', self.on_client_name_change)
        self.registerEvent('EVT_GAME_MAP_CHANGE', self.on_map_change)

        # install crontab
        self.crontab = b3.cron.PluginCronTab(self, self.execute_crontab, '*/%s' % self.interval)
        self.console.cron + self.crontab
Beispiel #19
0
    def onStartup(self):
        """
        Initialize plugin settings.
        """
        self.adminPlugin = self.console.getPlugin('admin')

        # create database tables (if needed)
        if 'callvote' not in self.console.storage.getTables():
            sql_path_main = b3.getAbsolutePath('@b3/plugins/callvote/sql')
            sql_path = os.path.join(sql_path_main, self.console.storage.dsnDict['protocol'], 'callvote.sql')
            self.console.storage.queryFromFile(sql_path)

        # unregister the veto command of the admin plugin
        if self.console.getPlugin('poweradminurt'):
            self.adminPlugin.unregisterCommand('paveto')

        # register our commands
        if 'commands' in self.config.sections():
            for cmd in self.config.options('commands'):
                level = self.config.get('commands', cmd)
                sp = cmd.split('-')
                alias = None
                if len(sp) == 2:
                    cmd, alias = sp

                func = getCmd(self, cmd)
                if func:
                    self.adminPlugin.registerCommand(self, cmd, level, func, alias)

        self.registerEvent('EVT_CLIENT_CALLVOTE', self.onCallvote)
        self.registerEvent('EVT_VOTE_PASSED', self.onCallvoteFinish)
        self.registerEvent('EVT_VOTE_FAILED', self.onCallvoteFinish)

        # notice plugin started
        self.debug('plugin started')
 def setUp(self):
     super(Test_Tk_default_config, self).setUp()
     self.console.gameName = 'f00'
     self.conf = CfgConfigParser()
     self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_tk.ini'))
     self.p = TkPlugin(self.console, self.conf)
     self.p.onLoadConfig()
 def getpath(self, section, setting):
     """
     Return an absolute path name and expand the user prefix (~).
     :param section: The configuration file section.
     :param setting: The configuration file setting.
     """
     return b3.getAbsolutePath(self.get(section, setting), decode=True)
    def setUp(self):

        B3TestCase.setUp(self)
        self.console.gameName = 'f00'

        self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
        when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        self.conf = CfgConfigParser()
        self.conf.loadFromString(dedent(r"""
            [commands]
            plugin: superadmin
        """))

        self.p = PluginmanagerPlugin(self.console, self.conf)
        when(self.console).getPlugin("pluginmanager").thenReturn(self.adminPlugin)
        self.p.onLoadConfig()
        self.p.onStartup()

        when(self.console.config).get_external_plugins_dir().thenReturn(b3.getAbsolutePath('@b3\\extplugins'))

        # store them also in the console _plugins dict
        self.console._plugins['admin'] = self.adminPlugin
        self.console._plugins['pluginmanager'] = self.p
Beispiel #23
0
 def setUp(self):
     super(Test_Tk_default_config, self).setUp()
     self.console.gameName = 'f00'
     self.conf = CfgConfigParser()
     self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_tk.ini'))
     self.p = TkPlugin(self.console, self.conf)
     self.p.onLoadConfig()
Beispiel #24
0
    def queryFromFile(self, fp, silent=False):
        """
        This method executes an external sql file on the current database.
        :param fp: The filepath of the file containing the SQL statements.
        :param silent: Whether or not to silence MySQL warnings.
        :raise Exception: If the query cannot be evaluated or if the given path cannot be resolved.
        """
        # use existing connection or create a new one
        # duplicate code of query() method which is needed not to spam the database
        # with useless connection attempts (one for each query in the SQL file)
        connection = self.getConnection()
        if not connection:
            raise Exception('lost connection with the storage layer during query')

        # save standard error output
        orig_stderr = sys.stderr
        if silent:
            # silence mysql warnings and such
            sys.stderr = open(os.devnull, 'w')

        path = b3.getAbsolutePath(fp)
        if not os.path.exists(path):
            raise Exception('SQL file does not exist: %s' % path)

        with open(path, 'r') as sqlfile:
            statements = self.getQueriesFromFile(sqlfile)

        for stmt in statements:
            # will stop if a single query generate an exception
            self.query(stmt)

        # reset standard error output
        sys.stderr = orig_stderr
    def connect(self):
        """
        Establish and return a connection with the storage layer.
        Will store the connection object also in the 'db' attribute so in the future we can reuse it.
        :return The connection instance if established successfully, otherwise None.
        """
        # no need to catch ImportError since we already did that in __new__()
        # do not retry too soon because the MySQL server could
        # have connection troubles and we do not want to spam it
        if time() - self._lastConnectAttempt < self._reconnectDelay:
            self.db = None
            self.console.bot('New PostgreSQL database connection requested but last connection attempt '
                             'failed less than %s seconds ago: exiting...' % self._reconnectDelay)
        else:
            # close the active connection (if any)
            self.shutdown()
            self.console.bot('Connecting to PostgreSQL database: %(protocol)s://%(user)s:******@%(host)s:%(port)s%(path)s...', self.dsnDict)

            try:

                import psycopg2
                self.db = psycopg2.connect(host=self.dsnDict['host'],
                                           port=self.dsnDict['port'],
                                           user=self.dsnDict['user'],
                                           password=self.dsnDict['password'],
                                           database=self.dsnDict['path'][1:])

                self.db.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
                self.db.set_client_encoding("UTF8")

                self.console.bot('Successfully established a connection with PostgreSQL database')
                self._lastConnectAttempt = 0

                if self._consoleNotice:
                    self.console.screen.write('Connecting to DB : OK\n')
                    self._consoleNotice = False

                # check whether the database is ready for usage or if we have to import B3 sql files to generate necessary
                # tables: if database is empty, then then AdminPlugin will raise an exception upon loading hence B3 won't be
                # operational. I placed the check here since it doesn't make sense to keep loading plugins if B3 will crash.
                if not self.getTables():

                    try:
                        self.console.info("Missing PostgreSQL database tables: importing SQL file: %s..." % b3.getAbsolutePath("@b3/sql/postgresql/b3.sql"))
                        self.queryFromFile("@b3/sql/postgresql/b3.sql")
                    except Exception, e:
                        self.shutdown()
                        self.console.critical("Missing PostgreSQL database tables. You need to create the necessary tables for "
                                              "B3 to work. You can do so by importing the following SQL script into your "
                                              "database: %s. An attempt of creating tables automatically just failed: %s" %
                                              (b3.getAbsolutePath("@b3/sql/postgresql/b3.sql"), e))

            except Exception, e:
                self.console.error('Database connection failed: working in remote mode: %s - %s', e, extract_tb(sys.exc_info()[2]))
                self.db = None
                self._lastConnectAttempt = time()
                if self._consoleNotice:
                    self.console.screen.write('Connecting to DB : FAILED!\n')
                    self._consoleNotice = False
Beispiel #26
0
def run(config=None):
	if config:
		config = b3.getAbsolutePath(config)
	else:
		# search for the config file
		config = None
		for p in ('b3.xml', 'conf/b3.xml', 'b3/conf/b3.xml', '~/b3.xml', '~/conf/b3.xml', '~/b3/conf/b3.xml', '@b3/conf/b3.xml'):
			path = b3.getAbsolutePath(p)
			print 'Searching for config file: %s' % path
			if os.path.isfile(path):
				config = path
				break

	if not config:
		raise SystemExit('Could not find config file.')

	b3.start(config)
 def _search_config_file(match):
     """
     Helper that returns a list of available configuration file paths for the given plugin.
     :param match: The plugin name
     """
     # first look in the built-in plugins directory
     search = '%s%s*%s*' % (b3.getAbsolutePath('@b3\\conf'), os.path.sep, match)
     self.debug('searching for configuration file(s) matching: %s' % search)
     collection = glob.glob(search)
     if len(collection) > 0:
         return collection
     # if none is found, then search in the extplugins directory
     extplugins_dir = self.console.config.get_external_plugins_dir()
     search = '%s%s*%s*' % (os.path.join(b3.getAbsolutePath(extplugins_dir), match, 'conf'), os.path.sep, match)
     self.debug('searching for configuration file(s) matching: %s' % search)
     collection = glob.glob(search)
     return collection
Beispiel #28
0
def run(config=None):
    if config:
        config = b3.getAbsolutePath(config)
    else:
        # search for the config file
        config = None
        for p in ('b3.xml', 'conf/b3.xml', 'b3/conf/b3.xml', '~/b3.xml', '~/conf/b3.xml', '~/b3/conf/b3.xml', '@b3/conf/b3.xml'):
            path = b3.getAbsolutePath(p)
            print 'Searching for config file: %s' % path
            if os.path.isfile(path):
                config = path
                break

    if not config:
        #Setup(config)
        raise SystemExit('ERROR: Could not find config file, Please run B3 with option: --setup or -s')

    b3.start(config)
Beispiel #29
0
 def test_default_conf(self):
     with open(b3.getAbsolutePath('@b3/conf/plugin_censor.xml')) as default_conf:
         self.init_plugin(default_conf.read())
     self.assertEqual(40, self.p._maxLevel)
     self.assertEqual(3, self.p._ignoreLength)
     self.assertEqual(68, len(self.p._badWords))
     self.assertEqual(17, len(self.p._badNames))
     self.assert_default_badwords_penalty()
     self.assert_default_badnames_penalty()
Beispiel #30
0
    def connect(self):
        """
        Establish and return a connection with the storage layer.
        Will store the connection object also in the 'db' attribute so in the future we can reuse it.
        :return The connection instance if established successfully, otherwise None.
        """
        # do not retry too soon because the MySQL server could
        # have connection troubles and we do not want to spam it
        if time() - self._lastConnectAttempt < self._reconnectDelay:
            self.db = None
            self.console.bot('New MySQL database connection requested but last connection attempt '
                             'failed less than %s seconds ago: exiting...' % self._reconnectDelay)
        else:
            # close the active connection (if any)
            self.shutdown()
            self.console.bot('Connecting to MySQL database: %(protocol)s://%(user)s:******@%(host)s:%(port)s%(path)s...', self.dsnDict)

            try:
                # create the connection instance using the specified connector
                self.db = self.__driver.connect(host=self.dsnDict['host'],
                                                port=self.dsnDict['port'],
                                                user=self.dsnDict['user'],
                                                passwd=self.dsnDict['password'],
                                                db=self.dsnDict['path'][1:],
                                                charset="utf8")

                self.console.bot('Successfully established a connection with MySQL database')
                self._lastConnectAttempt = 0

                if self._consoleNotice:
                    self.console.screen.write('Connecting to DB : OK\n')
                    self._consoleNotice = False

                # check whether the database is ready for usage or if we have to import B3 sql files to generate necessary
                # tables: if database is empty, then then AdminPlugin will raise an exception upon loading hence B3 won't be
                # operational. I placed the check here since it doesn't make sense to keep loading plugins if B3 will crash.
                if not self.getTables():

                    try:
                        self.console.info("Missing MySQL database tables: importing SQL file: %s..." % b3.getAbsolutePath("@b3/sql/mysql/b3.sql"))
                        self.queryFromFile("@b3/sql/mysql/b3.sql")
                    except Exception as e:
                        self.shutdown()
                        self.console.critical("Missing MySQL database tables. You need to create the necessary tables for "
                                              "B3 to work. You can do so by importing the following SQL script into your "
                                              "database: %s. An attempt of creating tables automatically just failed: %s" %
                                              (b3.getAbsolutePath("@b3/sql/mysql/b3.sql"), e))
            except Exception as e:
                self.console.error('Database connection failed: working in remote mode: %s - %s', e, extract_tb(sys.exc_info()[2]))
                self.db = None
                self._lastConnectAttempt = time()
                if self._consoleNotice:
                    self.console.screen.write('Connecting to DB : FAILED!\n')
                    self._consoleNotice = False

        return self.db
Beispiel #31
0
 def test_default_conf(self):
     with open(b3.getAbsolutePath(
             '@b3/conf/plugin_censor.xml')) as default_conf:
         self.init_plugin(default_conf.read())
     self.assertEqual(40, self.p._maxLevel)
     self.assertEqual(3, self.p._ignoreLength)
     self.assertEqual(68, len(self.p._badWords))
     self.assertEqual(17, len(self.p._badNames))
     self.assert_default_badwords_penalty()
     self.assert_default_badnames_penalty()
 def init(self, config_content=None):
     """
     Optionally specify a config for the plugin. If called with no parameter, then the default config is loaded.
     """
     if config_content is None:
         self.conf.load(b3.getAbsolutePath("@b3/conf/plugin_admin.ini"))
     else:
         self.conf.loadFromString(config_content)
     self.p.onLoadConfig()
     self.p.onStartup()
Beispiel #33
0
 def load_config(self, config_content=None):
     """
     load the given config content, or the default config if config_content is None.
     """
     if config_content is None:
         self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_welcome.ini'))
     else:
         self.conf.loadFromString(config_content)
     self.p.onLoadConfig()
     self.p.onStartup()
 def init(self, config_content=None):
     """
     Optionally specify a config for the plugin. If called with no parameter, then the default config is loaded.
     """
     if config_content is None:
         self.conf.load(b3.getAbsolutePath("@b3/conf/plugin_admin.ini"))
     else:
         self.conf.loadFromString(config_content)
     self.p.onLoadConfig()
     self.p.onStartup()
Beispiel #35
0
 def executeSql(self, filename):
     """This method executes an external sql file"""
     sqlFile = b3.getAbsolutePath(filename)
     f = open(sqlFile, 'r')
     sql_text = f.read()
     f.close()
     sql_statements = sql_text.split(';')
     for s in sql_statements:
         if len(s.strip()):
             self.query(s)
 def executeSql(self, filename):
     """This method executes an external sql file"""
     sqlFile = b3.getAbsolutePath(filename)
     f = open(sqlFile, "r")
     sql_text = f.read()
     f.close()
     sql_statements = sql_text.split(";")
     for s in sql_statements:
         if len(s.strip()):
             self.query(s)
 def load_config(self, config_content=None):
     """
     load the given config content, or the default config if config_content is None.
     """
     if config_content is None:
         self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_welcome.ini'))
     else:
         self.conf.loadFromString(config_content)
     self.p.onLoadConfig()
     self.p.onStartup()
Beispiel #38
0
def run(config=None, nosetup=False):
    if config:
        config = b3.getAbsolutePath(config)
    else:
        # search for the config file
        config = None
        for p in ('b3.xml', 'conf/b3.xml', 'b3/conf/b3.xml', '~/b3.xml', '~/conf/b3.xml', '~/b3/conf/b3.xml', '@b3/conf/b3.xml'):
            path = b3.getAbsolutePath(p)
            print 'Searching for config file: %s' % path
            if os.path.isfile(path):
                config = path
                break

    if not config:
        # This happens when no config was specified on the commandline and the default configs are missing! 
        if nosetup:
            raise SystemExit('ERROR: Could not find config file, Please run B3 with option: --setup or -s')
        else:
            Setup(config)

    b3.start(config, nosetup)
Beispiel #39
0
    def init(self, config_content=None):
        """ optionally specify a config for the plugin. If called with no parameter, then the default config is loaded """
        if config_content is None:
            self.conf.load(b3.getAbsolutePath("@b3/conf/plugin_admin.ini"))
        else:
            self.conf.loadFromString(config_content)

        self.p._commands = {}
        self.p.onLoadConfig()
        self.p.onStartup()

        self.joe = FakeClient(self.console, name="Joe", exactName="Joe", guid="joeguid", groupBits=128, team=TEAM_RED)
        self.mike = FakeClient(self.console, name="Mike", exactName="Mike", guid="mikeguid", groupBits=1, team=TEAM_BLUE)
    def init_plugin(self, config_content=None):
        self.conf = CfgConfigParser()
        if config_content:
            self.conf.loadFromString(config_content)
        else:
            self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_login.ini'))
        self.p = LoginPlugin(self.console, self.conf)

        self.log.setLevel(logging.DEBUG)
        self.log.info("============================= Login plugin: loading config ============================")
        self.p.onLoadConfig()
        self.log.info("============================= Login plugin: starting  =================================")
        self.p.onStartup()
    def setUp(self):
        super(Test_Censor_badname_default_config, self).setUp()

        def my_info(text):
            print("INFO\t%s" % text)
        #self.p.info = my_info

        def my_warning(text):
            print("WARNING\t%s" % text)
        #self.p.warning = my_warning

        self.p.config.load(b3.getAbsolutePath('@b3/conf/plugin_censor.xml'))
        self.p.onLoadConfig()
        self.assertEqual(17, len(self.p._badNames))
 def test_value_retrieval_valid(self):
     self.assertEqual(self.p.getSetting('section_foo', 'option_str', b3.STRING), 'string value with spaces')
     self.assertEqual(self.p.getSetting('section_foo', 'option_int', b3.STRING), '7')
     self.assertEqual(self.p.getSetting('section_foo', 'option_int', b3.INTEGER), 7)
     self.assertEqual(self.p.getSetting('section_foo', 'option_bool1', b3.BOOLEAN), False)
     self.assertEqual(self.p.getSetting('section_foo', 'option_bool2', b3.BOOLEAN), True)
     self.assertEqual(self.p.getSetting('section_foo', 'option_bool3', b3.BOOLEAN), False)
     self.assertEqual(self.p.getSetting('section_foo', 'option_bool4', b3.BOOLEAN), True)
     self.assertEqual(self.p.getSetting('section_foo', 'option_float', b3.STRING), '0.97')
     self.assertEqual(self.p.getSetting('section_foo', 'option_float', b3.FLOAT), 0.97)
     self.assertEqual(self.p.getSetting('section_foo', 'option_level1', b3.LEVEL), 80)
     self.assertEqual(self.p.getSetting('section_foo', 'option_level2', b3.LEVEL), 0)
     self.assertEqual(self.p.getSetting('section_foo', 'option_duration1', b3.DURATION), 300)
     self.assertEqual(self.p.getSetting('section_foo', 'option_duration2', b3.DURATION), 180)
     self.assertEqual(self.p.getSetting('section_foo', 'option_path', b3.PATH), b3.getAbsolutePath('@b3/conf/b3.distribution.ini', decode=True))
Beispiel #43
0
 def get_host_keys_file(self):
     """
     Get the path of the host keys file.
     The host key file can either be defined in the plugin config file or well known locations:
         ~/.ssh/known_hosts
         ~/ssh/known_hosts
     """
     host_keys_file = self.known_hosts_file
     for potential_location in ['~/.ssh/known_hosts', '~/ssh/known_hosts']:
         if host_keys_file is not None:
             break
         path = b3.getAbsolutePath(potential_location)
         if os.path.isfile(path):
             host_keys_file = path
     return host_keys_file
Beispiel #44
0
def load(filename):
    """
    Load a configuration file.
    Will instantiate the correct configuration object parser.
    """
    if os.path.splitext(filename)[1].lower() == '.xml':
        config = XmlConfigParser()
    else:
        # allow the use of empty keys to support the new b3.ini configuration file
        config = CfgConfigParser(allow_no_value=True)

    filename = b3.getAbsolutePath(filename, True)

    # return the config if it can be loaded
    return config if config.load(filename) else None
Beispiel #45
0
 def get_host_keys_file(self):
     """
     Get the path of the host keys file.
     The host key file can either be defined in the plugin config file or well known locations:
         ~/.ssh/known_hosts
         ~/ssh/known_hosts
     """
     host_keys_file = self.known_hosts_file
     for potential_location in ['~/.ssh/known_hosts', '~/ssh/known_hosts']:
         if host_keys_file is not None:
             break
         path = b3.getAbsolutePath(potential_location)
         if os.path.isfile(path):
             host_keys_file = path
     return host_keys_file
def load(filename):
    """
    Load a configuration file.
    Will instantiate the correct configuration object parser.
    """
    if os.path.splitext(filename)[1].lower() == '.xml':
        config = XmlConfigParser()
    else:
        # allow the use of empty keys to support the new b3.ini configuration file
        config = CfgConfigParser(allow_no_value=True)

    filename = b3.getAbsolutePath(filename, True)

    # return the config if it can be loaded
    return config if config.load(filename) else None
Beispiel #47
0
def run(config=None, nosetup=False):
    if config:
        config = b3.getAbsolutePath(config)
    else:
        # search for the config file
        config = None
        for p in ('b3.xml', 'conf/b3.xml', 'b3/conf/b3.xml', '~/b3.xml',
                  '~/conf/b3.xml', '~/b3/conf/b3.xml', '@b3/conf/b3.xml'):
            path = b3.getAbsolutePath(p)
            print 'Searching for config file: %s' % path
            if os.path.isfile(path):
                config = path
                break

    if not config:
        # This happens when no config was specified on the commandline and the default configs are missing!
        if nosetup:
            raise SystemExit(
                'ERROR: Could not find config file, Please run B3 with option: --setup or -s'
            )
        else:
            Setup(config)

    b3.start(config, nosetup)
Beispiel #48
0
 def test_value_retrieval_valid(self):
     self.assertEqual(self.p.getSetting('section_foo', 'option_str', b3.STRING), 'string value with spaces')
     self.assertEqual(self.p.getSetting('section_foo', 'option_int', b3.STRING), '7')
     self.assertEqual(self.p.getSetting('section_foo', 'option_int', b3.INTEGER), 7)
     self.assertEqual(self.p.getSetting('section_foo', 'option_bool1', b3.BOOLEAN), False)
     self.assertEqual(self.p.getSetting('section_foo', 'option_bool2', b3.BOOLEAN), True)
     self.assertEqual(self.p.getSetting('section_foo', 'option_bool3', b3.BOOLEAN), False)
     self.assertEqual(self.p.getSetting('section_foo', 'option_bool4', b3.BOOLEAN), True)
     self.assertEqual(self.p.getSetting('section_foo', 'option_float', b3.STRING), '0.97')
     self.assertEqual(self.p.getSetting('section_foo', 'option_float', b3.FLOAT), 0.97)
     self.assertEqual(self.p.getSetting('section_foo', 'option_level1', b3.LEVEL), 80)
     self.assertEqual(self.p.getSetting('section_foo', 'option_level2', b3.LEVEL), 0)
     self.assertEqual(self.p.getSetting('section_foo', 'option_duration1', b3.DURATION), 300)
     self.assertEqual(self.p.getSetting('section_foo', 'option_duration2', b3.DURATION), 180)
     self.assertEqual(self.p.getSetting('section_foo', 'option_path', b3.PATH), b3.getAbsolutePath('@b3/conf/b3.distribution.ini', decode=True))
    def setUp(self):
        super(Test_Censor_badname_default_config, self).setUp()

        def my_info(text):
            print("INFO\t%s" % text)

        #self.p.info = my_info

        def my_warning(text):
            print("WARNING\t%s" % text)

        #self.p.warning = my_warning

        self.p.config.load(b3.getAbsolutePath('@b3/conf/plugin_censor.xml'))
        self.p.onLoadConfig()
        self.assertEqual(17, len(self.p._badNames))
Beispiel #50
0
    def setUp(self):
        self.log = logging.getLogger('output')
        self.log.propagate = False

        B3TestCase.setUp(self)

        admin_conf = CfgConfigParser()
        admin_conf.load(b3.getAbsolutePath('@b3/conf/plugin_admin.ini'))
        self.adminPlugin = AdminPlugin(self.console, admin_conf)
        when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        self.console.gameName = "theGame"
        self.console.startup()
        self.log.propagate = True
    def setUp(self):
        SpamcontrolTestCase.setUp(self)

        self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
        when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        with open(b3.getAbsolutePath('@b3/conf/plugin_spamcontrol.ini')) as default_conf:
            self.init_plugin(default_conf.read())

        self.joe = FakeClient(self.console, name="Joe", guid="zaerezarezar", groupBits=1)
        self.joe.connects("1")

        self.superadmin = FakeClient(self.console, name="Superadmin", guid="superadmin_guid", groupBits=128)
        self.superadmin.connects("2")
Beispiel #52
0
 def _update_database(storage, update_version):
     """
     Update a B3 database.
     :param storage: the initialized storage module
     :param update_version: the update version
     """
     if B3version(b3.__version__) >= update_version:
         sql = b3.getAbsolutePath('@b3/sql/%s/b3-update-%s.sql' % (storage.protocol, update_version))
         if os.path.isfile(sql):
             try:
                 print '>>> updating database to version %s' % update_version
                 sleep(.5)
                 storage.queryFromFile(sql)
             except Exception, err:
                 print 'WARNING: could not update database properly: %s' % err
                 sleep(3)
Beispiel #53
0
 def build_database_schema(self):
     """
     Build the database tables needed if not present
     """
     sql_main = os.path.join(b3.getAbsolutePath('@b3/extplugins/reportcod4/sql'), 'mysql')
     current_tables = self.get_tables()
     # current_tables = self.console.storage.getTables()
     for f in os.listdir(sql_main):
         if f[:len(f) - len('.sql')] in current_tables:
             self.debug('Table %s found' % f)
         else:
             # Attempt to create the SQL table if it doesn't exist
             self.debug('Table %s NOT found, attempting to create' % f[:len(f) - len('.sql')])
             table = open('%s\\%s' % (sql_main, f), 'r').read()
             self._query(table)
             self.debug('Table %s created' % f[:len(f) - len('.sql')])
Beispiel #54
0
    def init_plugin(self, config_content=None):
        self.conf = CfgConfigParser()
        if config_content:
            self.conf.loadFromString(config_content)
        else:
            self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_login.ini'))
        self.p = LoginPlugin(self.console, self.conf)

        self.log.setLevel(logging.DEBUG)
        self.log.info(
            "============================= Login plugin: loading config ============================"
        )
        self.p.onLoadConfig()
        self.log.info(
            "============================= Login plugin: starting  ================================="
        )
        self.p.onStartup()
Beispiel #55
0
 def queryFromFile(self, file, silent=False):
     """This method executes an external sql file on the current database"""
     if self.db or self.connect():
         orig_stderr = sys.stderr # save standard error output
         if silent:
             sys.stderr = open(os.devnull, 'w') # silence the mysql warnings for existing tables and such
         sqlFile = b3.getAbsolutePath(file)
         if os.path.exists(sqlFile):
             f = open(sqlFile, 'r')
             sql_text = f.read()
             f.close()
             sql_statements = sql_text.split(';')
             for s in sql_statements:
                 try:
                     self.query(s)
                 except:
                     pass
         else:
             raise Exception('sqlFile does not exist: %s' %sqlFile)
         sys.stderr = orig_stderr # reset standard error output
     return None