Example #1
0
class ShellDatabaseConnection(object):
    """Sets up a database connection

      - Connects to a database
      - Telling why if it failed
      - Runs database wizard if needed
      - Runs schema migration
      - Activates plugins
      - Sets up main branch
    """

    def __init__(self, options):
        self._options = options
        self._config = None
        self._ran_wizard = False

    def connect(self):
        self._load_configuration()
        self._maybe_run_first_time_wizard()
        self._try_connect()
        self._post_connect()

    def _load_configuration(self):
        from stoqlib.lib.configparser import StoqConfig
        log.debug('reading configuration')
        self._config = StoqConfig()
        if self._options.filename:
            self._config.load(self._options.filename)
        else:
            self._config.load_default()

    def _maybe_run_first_time_wizard(self):
        from stoqlib.gui.base.dialogs import run_dialog
        from stoq.gui.config import FirstTimeConfigWizard

        config_file = self._config.get_filename()
        if self._options.wizard or not os.path.exists(config_file):
            run_dialog(FirstTimeConfigWizard, None, self._options)
            self._ran_wizard = True

        if self._config.get('Database', 'enable_production') == 'True':
            run_dialog(FirstTimeConfigWizard, None, self._options, self._config)
            self._ran_wizard = True

    def _try_connect(self):
        from stoqlib.lib.message import error
        try:
            store_dsn = self._config.get_settings().get_store_dsn()
        except:
            type, value, trace = sys.exc_info()
            error(_("Could not open the database config file"),
                  _("Invalid config file settings, got error '%s', "
                    "of type '%s'") % (value, type))

        from stoqlib.database.exceptions import PostgreSQLError
        from stoq.lib.startup import setup

        # XXX: progress dialog for connecting (if it takes more than
        # 2 seconds) or creating the database
        log.debug('calling setup()')
        try:
            setup(self._config, self._options, register_station=False,
                  check_schema=False, load_plugins=False)
        except (StoqlibError, PostgreSQLError) as e:
            error(_('Could not connect to the database'),
                  'error=%s uri=%s' % (str(e), store_dsn))

    def _post_connect(self):
        self._check_schema_migration()
        self._check_branch()
        self._activate_plugins()

    def _check_schema_migration(self):
        from stoqlib.lib.message import error
        from stoqlib.database.migration import needs_schema_update
        from stoqlib.exceptions import DatabaseInconsistency
        if needs_schema_update():
            self._run_update_wizard()

        from stoqlib.database.migration import StoqlibSchemaMigration
        migration = StoqlibSchemaMigration()
        try:
            migration.check()
        except DatabaseInconsistency as e:
            error(_('The database version differs from your installed '
                    'version.'), str(e))

    def _activate_plugins(self):
        from stoqlib.lib.pluginmanager import get_plugin_manager
        manager = get_plugin_manager()
        manager.activate_installed_plugins()

    def _check_branch(self):
        from stoqlib.database.runtime import (get_default_store, new_store,
                                              get_current_station,
                                              set_current_branch_station)
        from stoqlib.domain.person import Company
        from stoqlib.lib.parameters import sysparam
        from stoqlib.lib.message import info

        default_store = get_default_store()
        set_current_branch_station(default_store, station_name=None)

        compaines = default_store.find(Company)
        if (compaines.count() == 0 or
            not sysparam.has_object('MAIN_COMPANY')):
            from stoqlib.gui.base.dialogs import run_dialog
            from stoqlib.gui.dialogs.branchdialog import BranchDialog
            if self._ran_wizard:
                info(_("You need to register a company before start using Stoq"))
            else:
                info(_("Could not find a company. You'll need to register one "
                       "before start using Stoq"))
            store = new_store()
            person = run_dialog(BranchDialog, None, store)
            if not person:
                raise SystemExit
            branch = person.branch
            sysparam.set_object(store, 'MAIN_COMPANY', branch)
            get_current_station(store).branch = branch
            store.commit()
            store.close()

    def _run_update_wizard(self):
        from stoqlib.gui.base.dialogs import run_dialog
        from stoq.gui.update import SchemaUpdateWizard
        retval = run_dialog(SchemaUpdateWizard, None)
        if not retval:
            raise SystemExit()
Example #2
0
class ShellDatabaseConnection(object):
    """Sets up a database connection

      - Connects to a database
      - Telling why if it failed
      - Runs database wizard if needed
      - Runs schema migration
      - Activates plugins
      - Sets up main branch
    """

    def __init__(self, options):
        self._options = options
        self._config = None
        self._ran_wizard = False

    def connect(self):
        self._load_configuration()
        self._maybe_run_first_time_wizard()
        self._try_connect()
        self._post_connect()

    def _load_configuration(self):
        from stoqlib.lib.configparser import StoqConfig
        log.debug('reading configuration')
        self._config = StoqConfig()
        if self._options.filename:
            self._config.load(self._options.filename)
        else:
            self._config.load_default()

    def _maybe_run_first_time_wizard(self):
        from stoqlib.gui.base.dialogs import run_dialog
        from stoq.gui.config import FirstTimeConfigWizard

        config_file = self._config.get_filename()
        if self._options.wizard or not os.path.exists(config_file):
            run_dialog(FirstTimeConfigWizard, None, self._options)
            self._ran_wizard = True

        if self._config.get('Database', 'enable_production') == 'True':
            run_dialog(FirstTimeConfigWizard, None, self._options, self._config)
            self._ran_wizard = True

    def _get_password(self):
        import binascii
        configdir = self._config.get_config_directory()
        filename = os.path.join(configdir, 'data')
        if not os.path.exists(filename):
            return

        with open(filename, 'rb') as f:
            return binascii.a2b_base64(f.read()).decode()

    def _try_connect(self):
        from stoqlib.lib.message import error
        try:
            store_uri = self._config.get_settings().get_store_uri()
        except Exception:
            type, value, trace = sys.exc_info()
            error(_("Could not open the database config file"),
                  _("Invalid config file settings, got error '%s', "
                    "of type '%s'") % (value, type))

        from stoqlib.database.exceptions import PostgreSQLError
        from stoqlib.database.runtime import get_default_store
        from stoqlib.exceptions import DatabaseError
        from stoqlib.lib.pgpass import write_pg_pass
        from stoq.lib.startup import setup

        # XXX: progress dialog for connecting (if it takes more than
        # 2 seconds) or creating the database
        log.debug('calling setup()')
        try:
            setup(self._config, self._options, register_station=False,
                  check_schema=False, load_plugins=False)
            # the setup call above is not really trying to connect (since
            # register_station, check_schema and load_plugins are all False).
            # Try to really connect here.
            get_default_store()
        except (StoqlibError, PostgreSQLError) as e:
            log.debug('Connection failed.')
            error(_('Could not connect to the database'),
                  'error=%s uri=%s' % (str(e), store_uri))
        except DatabaseError:
            log.debug('Connection failed. Tring to setup .pgpass')
            # This is probably a missing password configuration. Setup the
            # pgpass file and try again.
            try:
                password = self._get_password()
                if not password:
                    # There is no password stored in data file. Abort
                    raise
                from stoqlib.database.settings import db_settings
                write_pg_pass(db_settings.dbname, db_settings.address,
                              db_settings.port, db_settings.username, password)
                # Now that there is a pg_pass file, try to connect again
                get_default_store()
            except DatabaseError as e:
                log.debug('Connection failed again.')
                error(_('Could not connect to the database'),
                      'error=%s uri=%s' % (str(e), store_uri))

    def _post_connect(self):
        self._check_schema_migration()
        self._check_branch()
        self._activate_plugins()

    def _check_schema_migration(self):
        from stoqlib.lib.message import error
        from stoqlib.database.migration import needs_schema_update
        from stoqlib.exceptions import DatabaseInconsistency
        if needs_schema_update():
            self._run_update_wizard()

        from stoqlib.database.migration import StoqlibSchemaMigration
        migration = StoqlibSchemaMigration()
        try:
            migration.check()
        except DatabaseInconsistency as e:
            error(_('The database version differs from your installed '
                    'version.'), str(e))

    def _activate_plugins(self):
        from stoqlib.lib.pluginmanager import get_plugin_manager
        manager = get_plugin_manager()
        manager.activate_installed_plugins()

    def _check_branch(self):
        from stoqlib.database.runtime import (get_default_store, new_store,
                                              get_current_station,
                                              set_current_branch_station)
        from stoqlib.domain.person import Company
        from stoqlib.lib.parameters import sysparam
        from stoqlib.lib.message import info

        default_store = get_default_store()

        compaines = default_store.find(Company)
        if (compaines.count() == 0 or
                not sysparam.has_object('MAIN_COMPANY')):
            from stoqlib.gui.base.dialogs import run_dialog
            from stoqlib.gui.dialogs.branchdialog import BranchDialog
            if self._ran_wizard:
                info(_("You need to register a company before start using Stoq"))
            else:
                info(_("Could not find a company. You'll need to register one "
                       "before start using Stoq"))
            store = new_store()
            person = run_dialog(BranchDialog, None, store)
            if not person:
                raise SystemExit
            branch = person.branch
            sysparam.set_object(store, 'MAIN_COMPANY', branch)
            current_station = get_current_station(store)
            if current_station is not None:
                current_station.branch = branch
            store.commit()
            store.close()

        set_current_branch_station(default_store, station_name=None)

    def _run_update_wizard(self):
        from stoqlib.gui.base.dialogs import run_dialog
        from stoq.gui.update import SchemaUpdateWizard
        retval = run_dialog(SchemaUpdateWizard, None)
        if not retval:
            raise SystemExit()
Example #3
0
class ShellDatabaseConnection(object):
    """Sets up a database connection

      - Connects to a database
      - Telling why if it failed
      - Runs database wizard if needed
      - Runs schema migration
      - Activates plugins
      - Sets up main branch
    """

    def __init__(self, options):
        self._options = options
        self._config = None
        self._ran_wizard = False

    def connect(self):
        self._load_configuration()
        self._maybe_run_first_time_wizard()
        self._try_connect()
        self._post_connect()

    def _load_configuration(self):
        from stoqlib.lib.configparser import StoqConfig
        log.debug('reading configuration')
        self._config = StoqConfig()
        if self._options.filename:
            self._config.load(self._options.filename)
        else:
            self._config.load_default()

    def _maybe_run_first_time_wizard(self):
        from stoqlib.gui.base.dialogs import run_dialog
        from stoq.gui.config import FirstTimeConfigWizard

        config_file = self._config.get_filename()
        if self._options.wizard or not os.path.exists(config_file):
            run_dialog(FirstTimeConfigWizard, None, self._options)
            self._ran_wizard = True

        if self._config.get('Database', 'enable_production') == 'True':
            run_dialog(FirstTimeConfigWizard, None, self._options, self._config)
            self._ran_wizard = True

    def _try_connect(self):
        from stoqlib.lib.message import error
        try:
            store_dsn = self._config.get_settings().get_store_dsn()
        except:
            type, value, trace = sys.exc_info()
            error(_("Could not open the database config file"),
                  _("Invalid config file settings, got error '%s', "
                    "of type '%s'") % (value, type))

        from stoqlib.database.exceptions import PostgreSQLError
        from stoq.lib.startup import setup

        # XXX: progress dialog for connecting (if it takes more than
        # 2 seconds) or creating the database
        log.debug('calling setup()')
        try:
            setup(self._config, self._options, register_station=False,
                  check_schema=False, load_plugins=False)
        except (StoqlibError, PostgreSQLError) as e:
            error(_('Could not connect to the database'),
                  'error=%s uri=%s' % (str(e), store_dsn))

    def _post_connect(self):
        self._check_schema_migration()
        self._check_branch()
        self._activate_plugins()

    def _check_schema_migration(self):
        from stoqlib.lib.message import error
        from stoqlib.database.migration import needs_schema_update
        from stoqlib.exceptions import DatabaseInconsistency
        if needs_schema_update():
            self._run_update_wizard()

        from stoqlib.database.migration import StoqlibSchemaMigration
        migration = StoqlibSchemaMigration()
        try:
            migration.check()
        except DatabaseInconsistency as e:
            error(_('The database version differs from your installed '
                    'version.'), str(e))

    def _activate_plugins(self):
        from stoqlib.lib.pluginmanager import get_plugin_manager
        manager = get_plugin_manager()
        manager.activate_installed_plugins()

    def _check_branch(self):
        from stoqlib.database.runtime import (get_default_store, new_store,
                                              get_current_station,
                                              set_current_branch_station)
        from stoqlib.domain.person import Company
        from stoqlib.lib.parameters import sysparam
        from stoqlib.lib.message import info

        default_store = get_default_store()
        set_current_branch_station(default_store, station_name=None)

        compaines = default_store.find(Company)
        if (compaines.count() == 0 or
            not sysparam(default_store).MAIN_COMPANY):
            from stoqlib.gui.base.dialogs import run_dialog
            from stoqlib.gui.dialogs.branchdialog import BranchDialog
            if self._ran_wizard:
                info(_("You need to register a company before start using Stoq"))
            else:
                info(_("Could not find a company. You'll need to register one "
                       "before start using Stoq"))
            store = new_store()
            person = run_dialog(BranchDialog, None, store)
            if not person:
                raise SystemExit
            branch = person.branch
            sysparam(store).MAIN_COMPANY = branch.id
            get_current_station(store).branch = branch
            store.commit()
            store.close()

    def _run_update_wizard(self):
        from stoqlib.gui.base.dialogs import run_dialog
        from stoq.gui.update import SchemaUpdateWizard
        retval = run_dialog(SchemaUpdateWizard, None)
        if not retval:
            raise SystemExit()