Subversion Repositories basico

Rev

Rev 254 | Rev 264 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

"""
#!/usr/bin/python 3
# -*- coding: utf-8 -*-
# File: basico.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: Main entry point por Basico app
"""


import os
import sys
import traceback as tb
import signal
from datetime import datetime
# ~ import selenium
from basico.core.mod_env import LPATH, GPATH, FILE
from basico.core.mod_log import get_logger
from basico.services.srv_utils import Utils
from basico.services.srv_gui import GUI
from basico.services.srv_iconmgt import IconManager
from basico.services.srv_bnr import BackupRestoreMan
from basico.services.srv_sap import SAP
from basico.services.srv_settings import Settings
from basico.services.srv_uif import UIFuncs
from basico.services.srv_cb import Callback
from basico.services.srv_notify import Notification
from basico.services.srv_db import Database
from basico.services.srv_driver import SeleniumDriver
from basico.services.srv_cols import Collections
from basico.services.srv_annot import Annotation


class Basico(object):
    """
    Basico class
    """

    def __init__(self):
        """Main class: the entry point for Basico.
        It stands for Controller.
        """

        # ~ STATS['BASICO_STARTUP_START'] = datetime.now()

        # Create local paths if they do not exist
        for entry in LPATH:
            if not os.path.exists(LPATH[entry]):
                os.makedirs(LPATH[entry])

        # Truncate existing log file
        if os.path.exists(FILE['LOG']):
            flog = open(FILE['LOG'], 'w')
            flog.close()

        # Create logger
        self.log = get_logger(self.__class__.__name__, FILE['LOG'])
        self.debug("Starting Basico")

        self.services = {}
        try:
            services = {
                'GUI'           :   GUI(),
                'Utils'         :   Utils(),
                'UIF'           :   UIFuncs(),
                'SAP'           :   SAP(),
                'Settings'      :   Settings(),
                'Notify'        :   Notification(),
                'IM'            :   IconManager(),
                'Callbacks'     :   Callback(),
                'DB'            :   Database(),
                'Driver'        :   SeleniumDriver(),
                'Collections'   :   Collections(),
                'Annotation'    :   Annotation(),
                'BNR'           :   BackupRestoreMan()
            }

            for name in services:
                self.register_service(name, services[name])
        except Exception as error:
            self.log.error(error)
            raise


    def print_traceback(self):
        self.debug(tb.format_exc())


    def debug(self, message):
        """
        debug
        """

        self.log.debug("%18s | %s", self.__class__.__name__, message)


    def error(self, message):
        """
        error
        """

        self.log.error("%18s | %s", self.__class__.__name__, message)


    def setup(self):
        """
        Setup Basico Envrionment
        Info about ConfigParser options:
        https://docs.python.org/3/library/configparser.html#interpolation-of-values
        https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.optionxform
        """

        self.debug("Setting up Basico environment")
        self.debug("Global path: %s" % GPATH['ROOT'])
        self.debug("Local path: %s" % LPATH['ROOT'])


    def list_services(self):
        """Return a dictionary of services"""
        return self.services


    def get_service(self, name):
        """Get/Start a registered service
        @type name: name of the service
        @param name: given a service name it returns the associated
        class. If service was not running it is started.
        """

        try:
            service = self.services[name]
            if not service.is_started():
                service.start(self, name)
            return service
        except KeyError as service:
            self.log.error("Service %s not registered or not found", service)
            raise


    def register_service(self, name, service):
        """Register a new service
        @type name: string
        @param name: name of the service
        @type service: class
        @param service: class which contains the code
        """

        try:
            self.services[name] = service
        except KeyError as error:
            self.log.error(error)


    def deregister_service(self, name):
        """Deregister a running service
        @type name: string
        @param name: name of the service
        """

        self.services[name].end()
        self.services[name] = None
        # ~ self.debug("Service %s stopped" % name)


    def check(self):
        '''
        Check Basico environment
        '''

        # ~ utils = self.get_service("Utils")
        uif = self.get_service('UIF')
        driver = self.get_service('Driver')

        # Show Selenium version
        # ~ self.debug("Selenium version: %s" % selenium.__version__)

        # Check proper GTK version
        gtk_version = uif.check_gtk_version()

        # Check Gecko webdrver
        gecko_driver = driver.check()

        run = gtk_version and gecko_driver

        if run:
            self.debug("Basico environment ready!")
        else:
            self.log.error("Error(s) found checking Basico environment")

        return run




    def stop(self):
        """For each service registered, it executes the 'end' method
        (if any) to finalize them properly.
        """


        # Deregister all services loaded
        self.deregister_service('GUI')
        for name in self.services:
            try:
                if name != 'GUI':
                    self.deregister_service(name)
            except Exception:
                self.log.error(self.get_traceback())
                raise

        self.debug("Basico finished")


    def get_traceback(self):
        """
        get traceback
        """

        return tb.format_exc()


    def run(self):
        """
        Start Basico
        """

        bnr = self.get_service('BNR')
        gui = self.get_service('GUI')
        bnr.backup()
        gui.run()


def main():
    """
    Entry point
    """

    #DOC: http://stackoverflow.com/questions/16410852/keyboard-interrupt-with-with-python-gtk
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    basico = Basico()
    basico.setup()
    if basico.check():
        basico.run()
        sys.exit(0)
    else:
        sys.exit(-1)