Example #1
0
File: env.py Project: peuter/gosa
    def __init__(self):
        # Load configuration
        self.config = Config(config=Environment.config, noargs=Environment.noargs)
        self.log = logging.getLogger(__name__)
        self.id = platform.node()
        self.__db = {}
        self.__db_session = {}

        # Dump configuration
        if self.log.getEffectiveLevel() == logging.DEBUG:
            self.log.debug("configuration dump:")

            for section in self.config.getSections():
                self.log.debug("[%s]" % section)
                items = self.config.getOptions(section)

                for item in items:
                    self.log.debug("%s = %s" % (item, items[item]))

            self.log.debug("end of configuration dump")

        # Load base - we need one
        self.base = self.config.get("core.base")
        self.domain = self.config.get("core.domain", "default")

        self.uuid = self.config.get("core.id", default=None)
        if not self.uuid:
            self.log.warning("system has no id - falling back to configured hardware uuid")
            self.uuid = dmi_system("uuid")

            if not self.uuid:
                self.log.error("system has no id - please configure one in the core section")
                raise Exception("No system id found")
Example #2
0
    def __init__(self):
        # Load configuration
        self.config = Config(config=Environment.config,  noargs=Environment.noargs)
        self.log = logging.getLogger(__name__)

        self.id = platform.node()

        # Dump configuration
        #TODO: core.loglevel is gone
        if self.config.get("core.loglevel") == "DEBUG":
            self.log.debug("configuration dump:")

            for section in self.config.getSections():
                self.log.debug("[%s]" % section)
                items = self.config.getOptions(section)

                for item in items:
                    self.log.debug("%s = %s" % (item, items[item]))

            self.log.debug("end of configuration dump")

        # Initialized
        self.domain = self.config.get("core.domain", default="org.gosa")
        self.uuid = self.config.get("core.id", default=None)
        if not self.uuid:
            self.log.warning("system has no id - falling back to configured hardware uuid")
            self.uuid = dmi_system("uuid")

            if not self.uuid:
                self.log.error("system has no id - please configure one in the core section")
                raise Exception("No system id found")

        self.active = True
Example #3
0
File: env.py Project: gonicus/gosa
    def __init__(self):
        # Load configuration
        self.config = Config(config=Environment.config, noargs=Environment.noargs)
        self.log = logging.getLogger(__name__)
        self.id = platform.node()
        self.__db = {}
        self.__db_session = {}
        self.__db_factory = {}

        # Dump configuration
        if self.log.getEffectiveLevel() == logging.DEBUG:
            self.log.debug("configuration dump:")

            for section in self.config.getSections():
                self.log.debug("[%s]" % section)
                items = self.config.getOptions(section)

                for item in items:
                    self.log.debug("%s = %s" % (item, items[item]))

            self.log.debug("end of configuration dump")

        # Load base - we need one
        self.base = self.config.get("core.base")
        self.domain = self.config.get("core.domain", "default")

        self.uuid = self.config.get("core.id", default=None)
        self.mode = self.config.get("core.mode", default="backend")
        if self.mode not in ["backend", "proxy"]:
            raise Exception("Unknown mode: %s (only 'backend' or 'proxy' are allowed)" % self.mode)

        if not self.uuid:
            self.log.warning("system has no id - falling back to configured hardware uuid")
            self.uuid = dmi_system("uuid")

            if not self.uuid:
                self.log.error("system has no id - please configure one in the core section")
                raise Exception("No system id found")

        self.backend_index = self.config.getboolean("backend.index", default=True)
        if self.backend_index is False and self.config.get("backend.index-trigger") is not None \
                and os.path.exists(self.config.get("backend.index-trigger")):
            self.backend_index = True
            os.remove(self.config.get("backend.index-trigger"))
Example #4
0
File: env.py Project: gonicus/gosa
class Environment:
    """
    The global information container, used as a singleton.
    """
    config = None
    threads = []
    log = None
    id = None
    reset_requested = False
    noargs = False
    domain = None
    __instance = None
    __db = None
    __db_session = None
    __db_factory = None

    def __init__(self):
        # Load configuration
        self.config = Config(config=Environment.config, noargs=Environment.noargs)
        self.log = logging.getLogger(__name__)
        self.id = platform.node()
        self.__db = {}
        self.__db_session = {}
        self.__db_factory = {}

        # Dump configuration
        if self.log.getEffectiveLevel() == logging.DEBUG:
            self.log.debug("configuration dump:")

            for section in self.config.getSections():
                self.log.debug("[%s]" % section)
                items = self.config.getOptions(section)

                for item in items:
                    self.log.debug("%s = %s" % (item, items[item]))

            self.log.debug("end of configuration dump")

        # Load base - we need one
        self.base = self.config.get("core.base")
        self.domain = self.config.get("core.domain", "default")

        self.uuid = self.config.get("core.id", default=None)
        self.mode = self.config.get("core.mode", default="backend")
        if self.mode not in ["backend", "proxy"]:
            raise Exception("Unknown mode: %s (only 'backend' or 'proxy' are allowed)" % self.mode)

        if not self.uuid:
            self.log.warning("system has no id - falling back to configured hardware uuid")
            self.uuid = dmi_system("uuid")

            if not self.uuid:
                self.log.error("system has no id - please configure one in the core section")
                raise Exception("No system id found")

        self.backend_index = self.config.getboolean("backend.index", default=True)
        if self.backend_index is False and self.config.get("backend.index-trigger") is not None \
                and os.path.exists(self.config.get("backend.index-trigger")):
            self.backend_index = True
            os.remove(self.config.get("backend.index-trigger"))

    def requestRestart(self):
        self.log.warning("a component requested an environment reset")
        self.reset_requested = True

    def getDatabaseEngine(self, section, key="database"):
        """
        Return a database engine from the registry.

        ========= ============
        Parameter Description
        ========= ============
        section   name of the configuration section where the config is placed.
        key       optional value for the key where the database information is stored, defaults to *database*.
        ========= ============

        ``Return``: database engine
        """
        config_key = "%s.%s" % (section, key)
        index = "%s:%s" % (os.getpid(), config_key)

        if not index in self.__db:
            if not self.config.get(config_key):
                raise Exception("No database connection defined for '%s'!" % index)
            if self.config.get(config_key).startswith("sqlite://"):
                from sqlalchemy.pool import StaticPool
                self.__db[index] = create_engine(self.config.get(config_key),
                                                 connect_args={'check_same_thread': False},
                                                 poolclass=StaticPool, encoding="utf-8")
            else:
                self.__db[index] = create_engine(self.config.get(config_key), encoding="utf-8")

            #TODO: configure engine
            #self.__db[index] = create_engine(self.config.get(index),
            #        pool_size=40, pool_recycle=120, echo=True)

        return self.__db[index]

    def getDatabaseSession(self, section, key="database"):
        """
        Return a database session from the pool.

        ========= ============
        Parameter Description
        ========= ============
        section   name of the configuration section where the config is placed.
        key       optional value for the key where the database information is stored, defaults to *database*.
        ========= ============

        ``Return``: database session
        """
        index = "%s:%s.%s" % (os.getpid(), section, key)
        sql = self.getDatabaseEngine(section, key)
        if index not in self.__db_session:
            self.__db_session[index] = scoped_session(sessionmaker(autoflush=True, bind=sql))

        session = self.__db_session[index]()
        if self.mode == "proxy":
            # read only mode
            event.listen(session, "before_flush", before_proxy_flush)

        return session

    def getDatabaseFactory(self, section, key="database"):
        index = "%s.%s" % (section, key)
        if index not in self.__db_factory:
            self.log.debug("creating new DB factory for %s" % index)
            session_events = None

            if self.mode == "proxy":
                # read only mode
                session_events = [("before_flush", before_proxy_flush)]

            self.__db_factory[index] = SessionFactory(self.config.get(index), session_events=session_events)
        return self.__db_factory[index]

    def remove_flush_listeners(self):
        """
        remove all before_flush listeners, currently this is only use by a test,
        that switched between proxied and normal mode.
        """
        for session in self.__db_session.values():
            if event.contains(session, "before_flush", before_proxy_flush):
                event.remove(session, "before_flush", before_proxy_flush)
        self.__db_session = {}
        for factory in self.__db_factory.values():
            factory.reset_events()

    @staticmethod
    def getInstance():
        """
        Act like a singleton and return the
        :class:`gosa.common.env.Environment` instance.

        ``Return``: :class:`gosa.common.env.Environment`
        """
        if not Environment.__instance:
            Environment.__instance = Environment()
        return Environment.__instance

    @staticmethod
    def reset():
        if Environment.__instance:
            Environment.__instance = None
Example #5
0
File: env.py Project: peuter/gosa
class Environment:
    """
    The global information container, used as a singleton.
    """
    config = None
    threads = []
    log = None
    id = None
    reset_requested = False
    noargs = False
    domain = None
    __instance = None
    __db = None
    __db_session = None

    def __init__(self):
        # Load configuration
        self.config = Config(config=Environment.config, noargs=Environment.noargs)
        self.log = logging.getLogger(__name__)
        self.id = platform.node()
        self.__db = {}
        self.__db_session = {}

        # Dump configuration
        if self.log.getEffectiveLevel() == logging.DEBUG:
            self.log.debug("configuration dump:")

            for section in self.config.getSections():
                self.log.debug("[%s]" % section)
                items = self.config.getOptions(section)

                for item in items:
                    self.log.debug("%s = %s" % (item, items[item]))

            self.log.debug("end of configuration dump")

        # Load base - we need one
        self.base = self.config.get("core.base")
        self.domain = self.config.get("core.domain", "default")

        self.uuid = self.config.get("core.id", default=None)
        if not self.uuid:
            self.log.warning("system has no id - falling back to configured hardware uuid")
            self.uuid = dmi_system("uuid")

            if not self.uuid:
                self.log.error("system has no id - please configure one in the core section")
                raise Exception("No system id found")

    def requestRestart(self):
        self.log.warning("a component requested an environment reset")
        self.reset_requested = True

    def getDatabaseEngine(self, section, key="database"):
        """
        Return a database engine from the registry.

        ========= ============
        Parameter Description
        ========= ============
        section   name of the configuration section where the config is placed.
        key       optional value for the key where the database information is stored, defaults to *database*.
        ========= ============

        ``Return``: database engine
        """
        index = "%s.%s" % (section, key)

        if not index in self.__db:
            if not self.config.get(index):
                raise Exception("No database connection defined for '%s'!" % index)
            if self.config.get(index).startswith("sqlite://"):
                from sqlalchemy.pool import StaticPool
                self.__db[index] = create_engine(self.config.get(index),
                                                 connect_args={'check_same_thread': False},
                                                 poolclass=StaticPool, encoding="utf-8")
            else:
                self.__db[index] = create_engine(self.config.get(index), encoding="utf-8")

            #TODO: configure engine
            #self.__db[index] = create_engine(self.config.get(index),
            #        pool_size=40, pool_recycle=120, echo=True)

        return self.__db[index]

    def getDatabaseSession(self, section, key="database"):
        """
        Return a database session from the pool.

        ========= ============
        Parameter Description
        ========= ============
        section   name of the configuration section where the config is placed.
        key       optional value for the key where the database information is stored, defaults to *database*.
        ========= ============

        ``Return``: database session
        """
        index = "%s.%s" % (section, key)
        sql = self.getDatabaseEngine(section, key)
        if index not in self.__db_session:
            self.__db_session[index] = scoped_session(sessionmaker(autoflush=True, bind=sql))

        return self.__db_session[index]()

    @staticmethod
    def getInstance():
        """
        Act like a singleton and return the
        :class:`gosa.common.env.Environment` instance.

        ``Return``: :class:`gosa.common.env.Environment`
        """
        if not Environment.__instance:
            Environment.__instance = Environment()
        return Environment.__instance

    @staticmethod
    def reset():
        if Environment.__instance:
            Environment.__instance = None
Example #6
0
class Environment:
    """
    The global information container, used as a singleton.
    """
    threads = []
    locks = []
    id = None
    config = None
    log = None
    domain = ""
    config = None
    noargs = False
    __instance = None
    __db = {}

    def __init__(self):
        # Load configuration
        self.config = Config(config=Environment.config,  noargs=Environment.noargs)
        self.log = logging.getLogger(__name__)

        self.id = platform.node()

        # Dump configuration
        #TODO: core.loglevel is gone
        if self.config.get("core.loglevel") == "DEBUG":
            self.log.debug("configuration dump:")

            for section in self.config.getSections():
                self.log.debug("[%s]" % section)
                items = self.config.getOptions(section)

                for item in items:
                    self.log.debug("%s = %s" % (item, items[item]))

            self.log.debug("end of configuration dump")

        # Initialized
        self.domain = self.config.get("core.domain", default="org.gosa")
        self.uuid = self.config.get("core.id", default=None)
        if not self.uuid:
            self.log.warning("system has no id - falling back to configured hardware uuid")
            self.uuid = dmi_system("uuid")

            if not self.uuid:
                self.log.error("system has no id - please configure one in the core section")
                raise Exception("No system id found")

        self.active = True

    def getDatabaseEngine(self, section, key="database"):
        """
        Return a database engine from the registry.

        ========= ============
        Parameter Description
        ========= ============
        section   name of the configuration section where the config is placed.
        key       optional value for the key where the database information is stored, defaults to *database*.
        ========= ============

        ``Return``: database engine
        """
        index = "%s.%s" % (section, key)

        if not index in self.__db:
            self.__db[index] = create_engine(self.config.get(index),
                    pool_size=40, pool_recycle=120)

        return self.__db[index]

    def getDatabaseSession(self, section, key="database"):
        """
        Return a database session from the pool.

        ========= ============
        Parameter Description
        ========= ============
        section   name of the configuration section where the config is placed.
        key       optional value for the key where the database information is stored, defaults to *database*.
        ========= ============

        ``Return``: database session
        """
        sql = self.getDatabaseEngine(section, key)
        session = scoped_session(sessionmaker(autoflush=True))
        session.configure(bind=sql)
        return session()

    @staticmethod
    def getInstance():
        """
        Act like a singleton and return the
        :class:`gosa.common.env.Environment` instance.

        ``Return``: :class:`gosa.common.env.Environment`
        """
        if not Environment.__instance:
            Environment.__instance = Environment()
        return Environment.__instance

    @staticmethod
    def reset():
        if Environment.__instance:
            Environment.__instance = None