Example #1
0
    def set_value_generic(self, param_name, value):
        """Update the internal cache for a parameter

        :param param_name: the parameter name
        :param value: value
        :type value: unicode
        """
        # FIXME: Find a better way of doing this after we integrate stoq.link
        # better with Stoq.
        if param_name == 'ONLINE_SERVICES':
            from stoqlib.net.server import ServerProxy
            p = ServerProxy(timeout=5)
            threadit(lambda: p.check_running() and p.call('restart'))

        self._values[param_name] = value
Example #2
0
    def set_value_generic(self, param_name, value):
        """Update the internal cache for a parameter

        :param param_name: the parameter name
        :param value: value
        :type value: unicode
        """
        # FIXME: Find a better way of doing this after we integrate stoq.link
        # better with Stoq.
        if param_name == 'ONLINE_SERVICES':
            from stoqlib.net.server import ServerProxy
            p = ServerProxy(timeout=5)
            threadit(lambda: p.check_running() and p.call('restart'))

        self._values[param_name] = value
Example #3
0
        def migrate():
            server = ServerProxy()
            running = yield server.check_running()
            if running:
                yield server.call('pause_tasks')

            try:
                retval = yield migration.update_async(backup=backup)
            finally:
                # The schema was upgraded. If it was running before,
                # restart it so it can load the new code
                if running:
                    yield server.call('restart')

            api.asyncReturn(retval)
Example #4
0
File: status.py Project: stoq/stoq
class _ServerStatus(ResourceStatus):

    name = "stoqserver"
    label = _("Online Services")
    priority = 99

    def __init__(self):
        ResourceStatus.__init__(self)
        self._server = ServerProxy()

    def refresh(self):
        if not api.sysparam.get_bool("ONLINE_SERVICES"):
            self.status = ResourceStatus.STATUS_NA
            self.reason = _("Online services (Stoq.link integration, backup, " "etc) not enabled...")
            self.reason_long = _('Enable the parameter "Online Services" ' 'on the "Admin" app to solve this issue')
            return

        if self._server.check_running():
            self.status = self.STATUS_OK
            self.reason = _("Online services data hub is running fine.")
            self.reason_long = None
        else:
            self.status = ResourceStatus.STATUS_ERROR
            self.reason = _("Online services data hub not found...")
            package = '<a href="apt://stoq-server">stoq-server</a>'
            self.reason_long = safe_str(
                api.escape(_("Install and configure the %s package " "to solve this issue")) % (package,)
            )
Example #5
0
        def migrate(retval):
            server = ServerProxy()
            running = yield server.check_running()
            if running:
                yield server.call('pause_tasks')

            try:
                retval[0] = yield migration.update_async(backup=backup)
            finally:
                # The schema was upgraded. If it was running before,
                # restart it so it can load the new code
                if running:
                    yield server.call('restart')

                if reactor.running:
                    reactor.stop()
Example #6
0
class _ServerStatus(ResourceStatus):

    name = "stoqserver"
    label = _("Online Services")
    priority = 99

    def __init__(self):
        ResourceStatus.__init__(self)
        self._server = ServerProxy()

    def refresh(self):
        if not api.sysparam.get_bool('ONLINE_SERVICES'):
            self.status = ResourceStatus.STATUS_NA
            self.reason = (_("Online services (Stoq.link integration, backup, "
                             "etc) not enabled..."))
            self.reason_long = _('Enable the parameter "Online Services" '
                                 'on the "Admin" app to solve this issue')
            return

        if self._server.check_running():
            self.status = self.STATUS_OK
            self.reason = _("Online services data hub is running fine.")
            self.reason_long = None
        else:
            self.status = ResourceStatus.STATUS_ERROR
            self.reason = _("Online services data hub not found...")
            package = '<a href="apt://stoq-server">stoq-server</a>'
            self.reason_long = safe_str(
                api.escape(_("Install and configure the %s package "
                             "to solve this issue")) % (package, ))
Example #7
0
    def cmd_updateschema(self, options):
        """Update the database schema"""
        from stoqlib.database.migration import StoqlibSchemaMigration
        from stoqlib.lib.environment import is_developer_mode
        from stoqlib.net.server import ServerProxy

        self._read_config(options,
                          check_schema=False,
                          load_plugins=False,
                          register_station=False)

        # This is a little bit tricky to be able to apply the initial
        # plugin infrastructure
        migration = StoqlibSchemaMigration()

        if is_developer_mode():
            backup = False
        else:
            backup = options.disable_backup

        server = ServerProxy()
        running = server.check_running()
        if running:
            server.call('pause_tasks')

        try:
            retval = migration.update(backup=backup)
        finally:
            # The schema was upgraded. If it was running before,
            # restart it so it can load the new code
            if running:
                server.call('restart')

        return 0 if retval else 1
Example #8
0
    def cmd_updateschema(self, options):
        """Update the database schema"""
        from stoqlib.database.migration import StoqlibSchemaMigration
        from stoqlib.lib.environment import is_developer_mode
        from stoqlib.net.server import ServerProxy

        self._read_config(options, check_schema=False, load_plugins=False,
                          register_station=False)

        # This is a little bit tricky to be able to apply the initial
        # plugin infrastructure
        migration = StoqlibSchemaMigration()

        if is_developer_mode():
            backup = False
        else:
            backup = options.disable_backup

        server = ServerProxy()
        running = server.check_running()
        if running:
            server.call('pause_tasks')

        try:
            retval = migration.update(backup=backup)
        finally:
            # The schema was upgraded. If it was running before,
            # restart it so it can load the new code
            if running:
                server.call('restart')

        return 0 if retval else 1
Example #9
0
        def init():
            server = ServerProxy()
            running = yield server.check_running()
            if running:
                yield server.call('pause_tasks')
            # ServerProxy may have opened a store
            set_default_store(None)

            try:
                initialize_system(password=unicode(options.password),
                                  force=options.force, empty=options.empty)
            except ValueError as e:
                # Database server is missing pg_trgm
                if 'pg_trgm' in str(e):
                    api.asyncReturn(31)
                else:
                    raise

            if options.create_examples or options.demo:
                from stoqlib.importers.stoqlibexamples import create
                create(utilities=True)

            if options.register_station and not options.empty:
                self._register_station()

            if options.plugins:
                self._enable_plugins(unicode(options.plugins).split(','))

            if options.demo:
                self._enable_demo()

            config.flush()

            # The schema was upgraded. If it was running before,
            # restart it so it can load the new code
            if running:
                yield server.call('restart')
Example #10
0
class PinDialog(BaseEditor):
    gladefile = 'PinDialog'
    model_type = Settable
    title = _("Connect to Stoq.link")
    size = (400, 200)
    proxy_widgets = ['pin']
    confirm_widgets = proxy_widgets

    def __init__(self, store):
        super(PinDialog, self).__init__(store)
        self._processing = False
        self._done = False
        self._set_processing(False)

    #
    #   BaseEditor
    #

    def create_model(self, store):
        return Settable(pin=None)

    def setup_proxies(self):
        self.add_proxy(self.model, self.proxy_widgets)
        self._proxy = ServerProxy()

    def validate_confirm(self):
        if self._done:
            return True

        self._set_processing(True)
        self._register_link()
        return False

    def refresh_ok(self, validation_value):
        super(PinDialog, self).refresh_ok(
            validation_value and not self._processing)

    #
    #   Private
    #

    def _set_processing(self, processing):
        self._processing = processing
        self.main_dialog.ok_button.set_sensitive(self.is_valid and not processing)
        self.main_dialog.cancel_button.set_sensitive(not processing)
        if processing:
            self.reply_lbl.set_text(
                _("Setting up the connection. This may take a while..."))
        else:
            self.reply_lbl.set_text("")
        self.spinner.set_visible(processing)

    @api.async
    def _register_link(self):
        running = yield self._proxy.check_running()
        if running:
            pin = self.pin.read()
            try:
                rv = yield self._proxy.call('register_link', pin)
            except ServerError as e:
                warning(_("An error happened when trying to register "
                          "to Stoq.Link"), str(e))
            else:
                log.info("register_link succedded. Retval: %s", rv)
                # If no exception happened, that mens that the registration
                # has succeeded.
                # XXX: Better text here
                info(_("Stoq.Link registration successful! You may "
                       "manage your installation from there now"))
                self._done = True
                self.confirm()
        else:
            # TODO: Maybe we should add a link pointing to instructions
            # on how to get and install the stoq-server package?
            warning(_("Could not find an instance of Stoq Server running."))

        self._set_processing(False)
Example #11
0
    def cmd_init(self, options):
        """Creates and initializes a database"""
        # Create a database user before trying to connect
        if options.create_dbuser:
            if not options.username:
                raise SystemExit("This option requires a --username set")
            retval = self._create_dbuser(options.username)
            if retval != 0:
                return retval
        config = self._read_config(options,
                                   register_station=False,
                                   check_schema=False,
                                   load_plugins=False)

        from stoqlib.database.admin import initialize_system
        from stoqlib.database.runtime import set_default_store
        from stoqlib.database.settings import db_settings
        from stoqlib.lib.pgpass import write_pg_pass
        from stoqlib.net.server import ServerProxy
        if options.dbname:
            db_settings.dbname = options.dbname
        if options.address:
            db_settings.address = options.address
        if options.port:
            db_settings.port = options.port
        if options.username:
            db_settings.username = options.username
        if options.password:
            db_settings.password = options.password
            # a password was sent via command line. Make sure we can run psql by
            # setting up pgpass
            write_pg_pass(db_settings.dbname, db_settings.address,
                          db_settings.port, db_settings.username,
                          db_settings.password)

        server = ServerProxy()
        running = server.check_running()
        if running:
            server.call('pause_tasks')
        # ServerProxy may have opened a store
        set_default_store(None)

        try:
            initialize_system(password='',
                              force=options.force,
                              empty=options.empty)
        except ValueError as e:
            # Database server is missing pg_trgm
            if 'pg_trgm' in str(e):
                return 31
            else:
                raise

        if options.create_examples or options.demo:
            from stoqlib.importers.stoqlibexamples import create
            create(utilities=True)

        if options.register_station and not options.empty:
            self._register_station()

        if options.pre_plugins:
            self._register_plugins(str(options.pre_plugins).split(','))

        if options.plugins:
            self._enable_plugins(str(options.plugins).split(','))

        if options.demo:
            self._enable_demo()

        config.flush()

        # The schema was upgraded. If it was running before,
        # restart it so it can load the new code
        if running:
            server.call('restart')

        return 0
Example #12
0
 def setup_proxies(self):
     self.add_proxy(self.model, self.proxy_widgets)
     self._proxy = ServerProxy(timeout=60)
Example #13
0
class PinDialog(BaseEditor):
    gladefile = 'PinDialog'
    model_type = Settable
    title = _("Connect to Stoq.link")
    size = (400, 200)
    proxy_widgets = ['pin']
    confirm_widgets = proxy_widgets

    def __init__(self, store):
        super(PinDialog, self).__init__(store)
        self._setup_widgets()
        self._processing = False
        self._done = False
        self._set_processing(False)

    #
    #   BaseEditor
    #

    def create_model(self, store):
        return Settable(pin=None)

    def setup_proxies(self):
        self.add_proxy(self.model, self.proxy_widgets)
        self._proxy = ServerProxy(timeout=60)

    def validate_confirm(self):
        if self._done:
            return True

        self._set_processing(True)
        threadit(self._register_link)
        return False

    def refresh_ok(self, validation_value):
        super(PinDialog, self).refresh_ok(validation_value
                                          and not self._processing)

    #
    #   Private
    #

    def _setup_widgets(self):
        user_hash = api.sysparam.get_string('USER_HASH')
        url = "https://stoq.link?source=stoqpin&amp;hash={}".format(user_hash)
        self.stoq_link_url_label.set_markup(
            _('This will connect your Stoq installation to <a href="{}">Stoq.Link</a>.\n'
              'Enter the <b>PIN</b> received from it bellow:').format(url))

    def _set_processing(self, processing):
        self._processing = processing
        self.main_dialog.ok_button.set_sensitive(self.is_valid
                                                 and not processing)
        self.main_dialog.cancel_button.set_sensitive(not processing)
        if processing:
            self.reply_lbl.set_text(
                _("Setting up the connection. This may take a while..."))
        else:
            self.reply_lbl.set_text("")
        self.spinner.set_visible(processing)

    def _set_error(self, msg, long_msg=None):
        warning(msg, long_msg)
        self._set_processing(False)

    def _set_done(self):
        # XXX: Better text here
        info(
            _("Stoq.Link registration successful! You may "
              "manage your installation from there now"))
        self._done = True
        self.confirm()
        self._set_processing(False)

    def _register_link(self):
        running = self._proxy.check_running()
        if running:
            pin = self.pin.read()
            try:
                rv = self._proxy.call('register_link', pin)
            except ServerError as e:
                msg = _(
                    "An error happened when trying to register to Stoq.Link")
                schedule_in_main_thread(self._set_error, msg, str(e))
            else:
                log.info("register_link succedded. Retval: %s", rv)
                # If no exception happened, that mens that the registration
                # has succeeded.
                schedule_in_main_thread(self._set_done)
        else:
            # TODO: Maybe we should add a link pointing to instructions
            # on how to get and install the stoq-server package?
            msg = _("Could not find an instance of Stoq Server running.")
            long_msg = _("Please install the stoq-server package in the same "
                         "computer as the database and try again")
            schedule_in_main_thread(self._set_error, msg, long_msg)
Example #14
0
 def __init__(self):
     ResourceStatus.__init__(self)
     self._webservice = WebService()
     self._server = ServerProxy()
Example #15
0
class _BackupStatus(ResourceStatus):

    name = "backup"
    label = _("Backup")
    priority = 98

    def __init__(self):
        ResourceStatus.__init__(self)
        self._webservice = WebService()
        self._server = ServerProxy()

    @threaded
    def _get_key(self):
        return self._server.call('get_backup_key')

    @threaded
    def _get_server_status(self):
        request = self._webservice.status()
        return request.get_response()

    def refresh(self):
        if stoq.trial_mode:
            self.status = ResourceStatus.STATUS_NA
            self.reason = (_('Online features are not available in trial mode'))
            self.reason_long = _('Online features require a subscription of Stoq.link')
            return

        if not api.sysparam.get_bool('ONLINE_SERVICES'):
            self.status = ResourceStatus.STATUS_NA
            self.reason = _('Backup service not running because '
                            '"Online Services" is disabled')
            self.reason_long = _('Enable the parameter "Online Services" '
                                 'on the "Admin" app to solve this issue')
            return

        try:
            key = self._get_key()
        except ServerError:
            pass
        else:
            if not key:
                self.status = self.STATUS_WARNING
                self.reason = _("Backup key not configured")
                self.reason_long = _('Click on "Configure" button to '
                                     'configure the backup key')
                return

        try:
            response = self._get_server_status()
        except Exception as e:
            self.status = self.STATUS_WARNING
            self.reason = _("Could not communicate with Stoq.link")
            self.reason_long = str(e)
            return

        if response.status_code != 200:
            self.status = self.STATUS_WARNING
            self.reason = _("Could not communicate with Stoq.link")
            self.reason_long = None
            return

        data = response.json()
        if data['latest_backup_date']:
            backup_date = dateutil.parser.parse(data['latest_backup_date'])
            delta = datetime.datetime.today() - backup_date

            if delta.days > 3:
                self.status = self.STATUS_WARNING
                self.reason = _("Backup is late. Last backup date is %s") % (
                    backup_date.strftime('%x'))
                self.reason_long = _("Check your Stoq Server logs to see if "
                                     "there's any problem with it")
            else:
                self.status = self.STATUS_OK
                self.reason = _("Backup is up-to-date. Last backup date is %s") % (
                    backup_date.strftime('%x'))
                self.reason_long = None
        else:
            self.status = self.STATUS_WARNING
            self.reason = _("There's no backup data yet")
            self.reason_long = None

    def get_actions(self):
        if self.status != ResourceStatus.STATUS_NA:
            yield ResourceStatusAction(
                self, 'backup-now',
                _("Backup now"), self._on_backup_now, threaded=True)
            yield ResourceStatusAction(
                self, 'configure',
                _("Configure"), self._on_configure, threaded=False)

    def _on_configure(self):
        key = self._server.call('get_backup_key')

        with api.new_store() as store:
            rv = run_dialog(BackupSettingsEditor, None,
                            store, Settable(key=key))

        if rv:
            key = self._server.call('set_backup_key', rv.key)

    def _on_backup_now(self):
        self._server.call('backup_database')
Example #16
0
 def __init__(self):
     ResourceStatus.__init__(self)
     self._server = ServerProxy()
Example #17
0
 def setup_proxies(self):
     self.add_proxy(self.model, self.proxy_widgets)
     self._proxy = ServerProxy(timeout=60)
Example #18
0
class PinDialog(BaseEditor):
    gladefile = 'PinDialog'
    model_type = Settable
    title = _("Connect to Stoq.link")
    size = (400, 200)
    proxy_widgets = ['pin']
    confirm_widgets = proxy_widgets

    def __init__(self, store):
        super(PinDialog, self).__init__(store)
        self._setup_widgets()
        self._processing = False
        self._done = False
        self._set_processing(False)

    #
    #   BaseEditor
    #

    def create_model(self, store):
        return Settable(pin=None)

    def setup_proxies(self):
        self.add_proxy(self.model, self.proxy_widgets)
        self._proxy = ServerProxy(timeout=60)

    def validate_confirm(self):
        if self._done:
            return True

        self._set_processing(True)
        threadit(self._register_link)
        return False

    def refresh_ok(self, validation_value):
        super(PinDialog, self).refresh_ok(
            validation_value and not self._processing)

    #
    #   Private
    #

    def _setup_widgets(self):
        user_hash = api.sysparam.get_string('USER_HASH')
        url = "https://stoq.link?source=stoqpin&amp;hash={}".format(user_hash)
        self.stoq_link_url_label.set_markup(
            _('This will connect your Stoq installation to <a href="{}">Stoq.Link</a>.\n'
              'Enter the <b>PIN</b> received from it bellow:').format(url))

    def _set_processing(self, processing):
        self._processing = processing
        self.main_dialog.ok_button.set_sensitive(self.is_valid and not processing)
        self.main_dialog.cancel_button.set_sensitive(not processing)
        if processing:
            self.reply_lbl.set_text(
                _("Setting up the connection. This may take a while..."))
        else:
            self.reply_lbl.set_text("")
        self.spinner.set_visible(processing)

    def _set_error(self, msg, long_msg=None):
        warning(msg, long_msg)
        self._set_processing(False)

    def _set_done(self):
        # XXX: Better text here
        info(_("Stoq.Link registration successful! You may "
               "manage your installation from there now"))
        self._done = True
        self.confirm()
        self._set_processing(False)

    def _register_link(self):
        running = self._proxy.check_running()
        if running:
            pin = self.pin.read()
            try:
                rv = self._proxy.call('register_link', pin)
            except ServerError as e:
                msg = _("An error happened when trying to register to Stoq.Link")
                schedule_in_main_thread(self._set_error, msg, str(e))
            else:
                log.info("register_link succedded. Retval: %s", rv)
                # If no exception happened, that mens that the registration
                # has succeeded.
                schedule_in_main_thread(self._set_done)
        else:
            # TODO: Maybe we should add a link pointing to instructions
            # on how to get and install the stoq-server package?
            msg = _("Could not find an instance of Stoq Server running.")
            long_msg = _("Please install the stoq-server package in the same "
                         "computer as the database and try again")
            schedule_in_main_thread(self._set_error, msg, long_msg)
Example #19
0
File: status.py Project: stoq/stoq
 def __init__(self):
     ResourceStatus.__init__(self)
     self._server = ServerProxy()
Example #20
0
    def cmd_init(self, options):
        """Creates and initializes a database"""
        # Create a database user before trying to connect
        if options.create_dbuser:
            if not options.username:
                raise SystemExit(
                    "This option requires a --username set")
            retval = self._create_dbuser(options.username)
            if retval != 0:
                return retval
        config = self._read_config(options, register_station=False,
                                   check_schema=False,
                                   load_plugins=False)

        from stoqlib.database.admin import initialize_system
        from stoqlib.database.runtime import set_default_store
        from stoqlib.database.settings import db_settings
        from stoqlib.net.server import ServerProxy
        if options.dbname:
            db_settings.dbname = options.dbname
        if options.address:
            db_settings.address = options.address
        if options.port:
            db_settings.port = options.port
        if options.username:
            db_settings.username = options.username
        if options.password:
            db_settings.password = options.password

        server = ServerProxy()
        running = server.check_running()
        if running:
            server.call('pause_tasks')
        # ServerProxy may have opened a store
        set_default_store(None)

        try:
            initialize_system(password=unicode(options.password),
                              force=options.force, empty=options.empty)
        except ValueError as e:
            # Database server is missing pg_trgm
            if 'pg_trgm' in str(e):
                return 31
            else:
                raise

        if options.create_examples or options.demo:
            from stoqlib.importers.stoqlibexamples import create
            create(utilities=True)

        if options.register_station and not options.empty:
            self._register_station()

        if options.pre_plugins:
            self._register_plugins(unicode(options.pre_plugins).split(','))

        if options.plugins:
            self._enable_plugins(unicode(options.plugins).split(','))

        if options.demo:
            self._enable_demo()

        config.flush()

        # The schema was upgraded. If it was running before,
        # restart it so it can load the new code
        if running:
            server.call('restart')

        return 0
Example #21
0
File: status.py Project: stoq/stoq
class _BackupStatus(ResourceStatus):

    name = "backup"
    label = _("Backup")
    priority = 98

    def __init__(self):
        ResourceStatus.__init__(self)
        self._webservice = WebService()
        self._server = ServerProxy()

    def refresh(self):
        if not api.sysparam.get_bool("ONLINE_SERVICES"):
            self.status = ResourceStatus.STATUS_NA
            self.reason = _("Backup service not running because " '"Online Services" is disabled')
            self.reason_long = _('Enable the parameter "Online Services" ' 'on the "Admin" app to solve this issue')
            return

        try:
            key = self._server.call("get_backup_key")
        except ServerError:
            pass
        else:
            if not key:
                self.status = self.STATUS_WARNING
                self.reason = _("Backup key not configured")
                self.reason_long = _('Click on "Configure" button to ' "configure the backup key")
                return

        request = self._webservice.status()
        try:
            response = request.get_response()
        except Exception as e:
            self.status = self.STATUS_WARNING
            self.reason = _("Could not communicate with Stoq.link")
            self.reason_long = str(e)
            return

        if response.status_code != 200:
            self.status = self.STATUS_WARNING
            self.reason = _("Could not communicate with Stoq.link")
            self.reason_long = None
            return

        data = response.json()
        if data["latest_backup_date"]:
            backup_date = dateutil.parser.parse(data["latest_backup_date"])
            delta = datetime.datetime.today() - backup_date

            if delta.days > 3:
                self.status = self.STATUS_WARNING
                self.reason = _("Backup is late. Last backup date is %s") % (backup_date.strftime("%x"))
                self.reason_long = _("Check your Stoq Server logs to see if " "there's any problem with it")
            else:
                self.status = self.STATUS_OK
                self.reason = _("Backup is up-to-date. Last backup date is %s") % (backup_date.strftime("%x"))
                self.reason_long = None
        else:
            self.status = self.STATUS_WARNING
            self.reason = _("There's no backup data yet")
            self.reason_long = None

    def get_actions(self):
        if self.status != ResourceStatus.STATUS_NA:
            yield ResourceStatusAction(self, "backup-now", _("Backup now"), self._on_backup_now, threaded=True)
            yield ResourceStatusAction(self, "configure", _("Configure"), self._on_configure, threaded=False)

    def _on_configure(self):
        key = self._server.call("get_backup_key")

        with api.new_store() as store:
            rv = run_dialog(BackupSettingsEditor, None, store, Settable(key=key))

        if rv:
            key = self._server.call("set_backup_key", rv.key)

    def _on_backup_now(self):
        self._server.call("backup_database")
Example #22
0
File: status.py Project: stoq/stoq
 def __init__(self):
     ResourceStatus.__init__(self)
     self._webservice = WebService()
     self._server = ServerProxy()