예제 #1
0
    def test_set_and_save(self):
        config = self._read()
        config.set('b', 'option0', 'y')
        config.set('a', 'option0', 'x')
        config.set('a', 'option2', "Voilà l'été")  # UTF-8
        config.set('a', 'option1', u"Voilà l'été") # unicode
        # Note: the following would depend on the locale.getpreferredencoding()
        # config.set('a', 'option3', "Voil\xe0 l'\xe9t\xe9") # latin-1
        self.assertEquals('x', config.get('a', 'option0'))
        self.assertEquals(u"Voilà l'été", config.get('a', 'option1'))
        self.assertEquals(u"Voilà l'été", config.get('a', 'option2'))
        config.save()

        configfile = open(self.filename, 'r')
        self.assertEquals(['# -*- coding: utf-8 -*-\n',
                           '\n',
                           '[a]\n',
                           'option0 = x\n', 
                           "option1 = Voilà l'été\n", 
                           "option2 = Voilà l'été\n", 
                           # "option3 = Voilà l'été\n", 
                           '\n',
                           '[b]\n',
                           'option0 = y\n', 
                           '\n'],
                          configfile.readlines())
        configfile.close()
        config2 = Configuration(self.filename)
        self.assertEquals('x', config2.get('a', 'option0'))
        self.assertEquals(u"Voilà l'été", config2.get('a', 'option1'))
        self.assertEquals(u"Voilà l'été", config2.get('a', 'option2'))
예제 #2
0
파일: env.py 프로젝트: barsch/seishub.core
class Environment(ComponentManager):
    """
    The one class to rule them all.
    
    Environment is the base class to handle configuration, XML catalog, 
    database and logging access.
    
    A SeisHub environment consists of:
        * a configuration handler env.config
        * a XML catalog handler env.catalog
        * a database handler env.db
        * a logging handler env.log
        * a package handler env.registry
        * a user management handler env.auth
    """
    Option('seishub', 'host', 'localhost', "Default host of this server.")
    BoolOption('seishub', 'use_trash_folder', False,
               "Mode deleted resources into a trash folder.")

    def __init__(self, path, application=None, config_file="seishub.ini",
                 log_file="seishub.log", create=None):
        """
        Initialize the SeisHub environment.
        """
        # set application
        self.app = application
        self._path = path
        # check Python version
        if not sys.hexversion >= 0x2060000:
            print("ERROR: SeisHub needs at least Python 2.6 or higher in " +
                  "order to run.")
            exit()
        if not sys.hexversion <= 0x3000000:
            print("ERROR: SeisHub is not yet compatible with Python 3.x.")
            exit()
        # check if new environment must be created
        if create:
            self.create(path)
        # set a start up timestamp
        self.startup_time = int(time.time())
        # set configuration handler
        if isinstance(config_file, Configuration):
            self.config = config_file
        else:
            config_file = os.path.join(path, 'conf', config_file)
            self.config = Configuration(config_file)
        self.config.path = path
        self.config.hubs = {}
        # set log handler
        self.log = Logger(self, log_file)
        # initialize all default options
        self.initDefaultOptions()
        # set up DB handler
        self.db = DatabaseManager(self)
        # set up component manager
        ComponentManager.__init__(self)
        self.compmgr = self
        # initialize all default options
        self.initDefaultOptions()
        # set XML catalog
        self.catalog = XmlCatalog(self)
        # user and group management
        self.auth = AuthenticationManager(self)
        # load plug-ins
        ComponentLoader(self)
        # Package manager
        # initialize ComponentRegistry after ComponentLoader(), as plug-ins 
        # may provide registry objects
        self.registry = ComponentRegistry(self)
        # trigger auto installer
        PackageInstaller.install(self)
        # initialize the resource tree
        self.tree = ResourceTree(self)
        self.update()
        # XSLT transformation parameters
        self.xslt_params = {}
        # check if new environment has been created
        if create:
            exit()

    def create(self, path):
        """
        Creates a new SeisHub environment.
        """
        # create the directory structure
        if not os.path.exists(path):
            os.mkdir(path)
        print("Creating new SeisHub instance in %s" % path)
        os.mkdir(os.path.join(path, 'bin'))
        os.mkdir(os.path.join(path, 'conf'))
        os.mkdir(os.path.join(path, 'data'))
        os.mkdir(os.path.join(path, 'db'))
        os.mkdir(os.path.join(path, 'logs'))
        # create maintenance scripts
        fh = open(os.path.join(path, 'bin', 'debug.bat'), 'wt')
        fh.write(WIN_DEBUG % (sys.executable, path))
        fh.close()
        fh = open(os.path.join(path, 'bin', 'debug.sh'), 'wt')
        fh.write(BASH_DEBUG % (sys.executable, path))
        fh.close()
        fh = open(os.path.join(path, 'bin', 'start.sh'), 'wt')
        fh.write(BASH_START % (sys.executable, path))
        fh.close()
        fh = open(os.path.join(path, 'bin', 'stop.sh'), 'wt')
        fh.write(BASH_STOP % (path))
        fh.close()
        # set execution rights for linux
        try:
            os.chmod(os.path.join(path, 'bin', 'debug.sh'), 0744)
            os.chmod(os.path.join(path, 'bin', 'start.sh'), 0744)
            os.chmod(os.path.join(path, 'bin', 'stop.sh'), 0744)
        except:
            pass

    def getPackagePath(self):
        """
        Returns the absolute root path to the SeisHub module directory.
        """
        return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

    def getInstancePath(self):
        """
        Returns the absolute root path to the SeisHub instance directory.
        """
        return self._path

    def initDefaultOptions(self):
        """
        Initialize any not yet set default options in configuration file.
        """
        defaults = self.config.defaults()
        for section in defaults.keys():
            for name in defaults.get(section).keys():
                if self.config.has_site_option(section, name):
                    continue
                else:
                    value = defaults.get(section).get(name)
                    self.config.set(section, name, value)
                    self.log.info('Setting default value for [%s] %s = %s' \
                                  % (section, name, value))
                    self.config.save()

    def getRestUrl(self):
        """
        Returns the root URL of the REST pages.
        """
        rest_host = self.config.get('seishub', 'host') or 'localhost'
        rest_port = self.config.getint('web', 'http_port') or HTTP_PORT
        return 'http://' + rest_host + ':' + str(rest_port)

    def update(self):
        """
        General update method after enabling/disabling components.
        """
        self.registry.mappers.update()
        self.registry.formaters.update()
        self.registry.processor_indexes.update()
        self.tree.update()
        self.catalog.updateAllIndexViews()
        self.registry.sqlviews.update()

    @defer.inlineCallbacks
    def enableService(self, id):
        """
        Enable a service.
        """
        for srv in service.IServiceCollection(self.app):
            if srv.service_id == id:
                # ensure not to start a service twice; may be fatal with timers
                if srv.running:
                    self.log.info('Service %s already started.' % srv.name)
                    return
                self.config.set(srv.service_id, 'autostart', True)
                self.config.save()
                yield defer.maybeDeferred(srv.startService)
                self.log.info('Starting service %s.' % srv.name)

    @defer.inlineCallbacks
    def disableService(self, id):
        """
        Disable a service.
        """
        for srv in service.IServiceCollection(self.app):
            if srv.service_id == id:
                self.config.set(srv.service_id, 'autostart', False)
                self.config.save()
                yield defer.maybeDeferred(srv.stopService)
                self.log.info('Stopping service %s.' % srv.name)

    def enableComponent(self, component, update=True):
        """
        Enables a component.
        """
        module = sys.modules[component.__module__]
        fullname = module.__name__ + '.' + component.__name__
        if not component in self:
            self[component]
        self.enabled[component] = True
        self.config.set('components', fullname, 'enabled')
        self.config.save()
        # package installer must run first before saving
        if hasattr(component, 'package_id'):
            try:
                PackageInstaller.install(self, component.package_id)
            except Exception, e:
                self.disableComponent(component)
                return str(e)
        self.log.info('Enabling component %s' % fullname)
        if update:
            self.update()
예제 #3
0
class Environment(ComponentManager):
    """
    The one class to rule them all.
    
    Environment is the base class to handle configuration, XML catalog, 
    database and logging access.
    
    A SeisHub environment consists of:
        * a configuration handler env.config
        * a XML catalog handler env.catalog
        * a database handler env.db
        * a logging handler env.log
        * a package handler env.registry
        * a user management handler env.auth
    """
    Option('seishub', 'host', 'localhost', "Default host of this server.")
    BoolOption('seishub', 'use_trash_folder', False,
               "Mode deleted resources into a trash folder.")

    def __init__(self,
                 path,
                 application=None,
                 config_file="seishub.ini",
                 log_file="seishub.log",
                 create=None):
        """
        Initialize the SeisHub environment.
        """
        # set application
        self.app = application
        self._path = path
        # check Python version
        if not sys.hexversion >= 0x2060000:
            print("ERROR: SeisHub needs at least Python 2.6 or higher in " +
                  "order to run.")
            exit()
        if not sys.hexversion <= 0x3000000:
            print("ERROR: SeisHub is not yet compatible with Python 3.x.")
            exit()
        # check if new environment must be created
        if create:
            self.create(path)
        # set a start up timestamp
        self.startup_time = int(time.time())
        # set configuration handler
        if isinstance(config_file, Configuration):
            self.config = config_file
        else:
            config_file = os.path.join(path, 'conf', config_file)
            self.config = Configuration(config_file)
        self.config.path = path
        self.config.hubs = {}
        # set log handler
        self.log = Logger(self, log_file)
        # initialize all default options
        self.initDefaultOptions()
        # set up DB handler
        self.db = DatabaseManager(self)
        # set up component manager
        ComponentManager.__init__(self)
        self.compmgr = self
        # initialize all default options
        self.initDefaultOptions()
        # set XML catalog
        self.catalog = XmlCatalog(self)
        # user and group management
        self.auth = AuthenticationManager(self)
        # load plug-ins
        ComponentLoader(self)
        # Package manager
        # initialize ComponentRegistry after ComponentLoader(), as plug-ins
        # may provide registry objects
        self.registry = ComponentRegistry(self)
        # trigger auto installer
        PackageInstaller.install(self)
        # initialize the resource tree
        self.tree = ResourceTree(self)
        self.update()
        # XSLT transformation parameters
        self.xslt_params = {}
        # check if new environment has been created
        if create:
            exit()

    def create(self, path):
        """
        Creates a new SeisHub environment.
        """
        # create the directory structure
        if not os.path.exists(path):
            os.mkdir(path)
        print("Creating new SeisHub instance in %s" % path)
        os.mkdir(os.path.join(path, 'bin'))
        os.mkdir(os.path.join(path, 'conf'))
        os.mkdir(os.path.join(path, 'data'))
        os.mkdir(os.path.join(path, 'db'))
        os.mkdir(os.path.join(path, 'logs'))
        # create maintenance scripts
        fh = open(os.path.join(path, 'bin', 'debug.bat'), 'wt')
        fh.write(WIN_DEBUG % (sys.executable, path))
        fh.close()
        fh = open(os.path.join(path, 'bin', 'debug.sh'), 'wt')
        fh.write(BASH_DEBUG % (sys.executable, path))
        fh.close()
        fh = open(os.path.join(path, 'bin', 'start.sh'), 'wt')
        fh.write(BASH_START % (sys.executable, path))
        fh.close()
        fh = open(os.path.join(path, 'bin', 'stop.sh'), 'wt')
        fh.write(BASH_STOP % (path))
        fh.close()
        # set execution rights for linux
        try:
            os.chmod(os.path.join(path, 'bin', 'debug.sh'), 0744)
            os.chmod(os.path.join(path, 'bin', 'start.sh'), 0744)
            os.chmod(os.path.join(path, 'bin', 'stop.sh'), 0744)
        except:
            pass

    def getPackagePath(self):
        """
        Returns the absolute root path to the SeisHub module directory.
        """
        return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

    def getInstancePath(self):
        """
        Returns the absolute root path to the SeisHub instance directory.
        """
        return self._path

    def initDefaultOptions(self):
        """
        Initialize any not yet set default options in configuration file.
        """
        defaults = self.config.defaults()
        for section in defaults.keys():
            for name in defaults.get(section).keys():
                if self.config.has_site_option(section, name):
                    continue
                else:
                    value = defaults.get(section).get(name)
                    self.config.set(section, name, value)
                    self.log.info('Setting default value for [%s] %s = %s' \
                                  % (section, name, value))
                    self.config.save()

    def getRestUrl(self):
        """
        Returns the root URL of the REST pages.
        """
        rest_host = self.config.get('seishub', 'host') or 'localhost'
        rest_port = self.config.getint('web', 'http_port') or HTTP_PORT
        return 'http://' + rest_host + ':' + str(rest_port)

    def update(self):
        """
        General update method after enabling/disabling components.
        """
        self.registry.mappers.update()
        self.registry.formaters.update()
        self.registry.processor_indexes.update()
        self.tree.update()
        self.catalog.updateAllIndexViews()
        self.registry.sqlviews.update()

    @defer.inlineCallbacks
    def enableService(self, id):
        """
        Enable a service.
        """
        for srv in service.IServiceCollection(self.app):
            if srv.service_id == id:
                # ensure not to start a service twice; may be fatal with timers
                if srv.running:
                    self.log.info('Service %s already started.' % srv.name)
                    return
                self.config.set(srv.service_id, 'autostart', True)
                self.config.save()
                yield defer.maybeDeferred(srv.startService)
                self.log.info('Starting service %s.' % srv.name)

    @defer.inlineCallbacks
    def disableService(self, id):
        """
        Disable a service.
        """
        for srv in service.IServiceCollection(self.app):
            if srv.service_id == id:
                self.config.set(srv.service_id, 'autostart', False)
                self.config.save()
                yield defer.maybeDeferred(srv.stopService)
                self.log.info('Stopping service %s.' % srv.name)

    def enableComponent(self, component, update=True):
        """
        Enables a component.
        """
        module = sys.modules[component.__module__]
        fullname = module.__name__ + '.' + component.__name__
        if not component in self:
            self[component]
        self.enabled[component] = True
        self.config.set('components', fullname, 'enabled')
        self.config.save()
        # package installer must run first before saving
        if hasattr(component, 'package_id'):
            try:
                PackageInstaller.install(self, component.package_id)
            except Exception, e:
                self.disableComponent(component)
                return str(e)
        self.log.info('Enabling component %s' % fullname)
        if update:
            self.update()