def settings(self, save_settings=False, **data):
     """Main settings page submit and get"""
     template_specification = dict(mainContent="../settings/system_settings", title="System Settings")
     if save_settings:
         try:
             form = SettingsForm()
             data = form.to_python(data)
             isrestart, isreset = self.settingsservice.save_settings(**data)
             if isrestart:
                 thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset})
                 thread.start()
                 common.add2session(common.KEY_IS_RESTART, True)
                 common.set_important_message('Please wait until TVB is restarted properly!')
                 raise cherrypy.HTTPRedirect('/tvb')
             # Here we will leave the same settings page to be displayed.
             # It will continue reloading when CherryPy restarts.
         except formencode.Invalid as excep:
             template_specification[common.KEY_ERRORS] = excep.unpack_errors()
         except InvalidSettingsException as excep:
             self.logger.error('Invalid settings!  Exception %s was raised' % (str(excep)))
             common.set_error_message(excep.message)
     template_specification.update({'keys_order': self.settingsservice.KEYS_DISPLAY_ORDER,
                                    'config_data': self.settingsservice.configurable_keys,
                                    common.KEY_FIRST_RUN: TvbProfile.is_first_run()})
     return self.fill_default_attributes(template_specification)
Пример #2
0
 def settings(self, save_settings=False, **data):
     """Main settings page submit and get"""
     template_specification = dict(mainContent="settings/system_settings", title="System Settings")
     if save_settings:
         try:
             form = SettingsForm()
             data = form.to_python(data)
             isrestart, isreset = self.settingsservice.save_settings(**data)
             if isrestart:
                 thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset})
                 thread.start()
                 common.add2session(common.KEY_IS_RESTART, True)
                 common.set_important_message('Please wait until TVB is restarted properly!')
                 raise cherrypy.HTTPRedirect('/tvb')
             # Here we will leave the same settings page to be displayed.
             # It will continue reloading when CherryPy restarts.
         except formencode.Invalid as excep:
             template_specification[common.KEY_ERRORS] = excep.unpack_errors()
         except InvalidSettingsException as excep:
             self.logger.error('Invalid settings!  Exception %s was raised' % (str(excep)))
             common.set_error_message(excep.message)
     template_specification.update({'keys_order': self.settingsservice.KEYS_DISPLAY_ORDER,
                                    'config_data': self.settingsservice.configurable_keys,
                                    common.KEY_FIRST_RUN: TvbProfile.is_first_run()})
     return self.fill_default_attributes(template_specification)
Пример #3
0
def initialize(introspected_modules, load_xml_events=True):
    """
    Initialize when Application is starting.
    Check for new algorithms or new DataTypes.
    """
    SettingsService().check_db_url(TvbProfile.current.db.DB_URL)

    ## Initialize DB
    is_db_empty = initialize_startup()

    ## Create Projects storage root in case it does not exist.
    initialize_storage()

    ## Populate DB algorithms, by introspection
    event_folders = []
    start_introspection_time = datetime.datetime.now()
    for module in introspected_modules:
        introspector = Introspector(module)
        # Introspection is always done, even if DB was not empty.
        introspector.introspect(True)
        event_path = introspector.get_events_path()
        if event_path:
            event_folders.append(event_path)

    # Now remove or mark as removed any unverified Algo-Group, Algo-Category or Portlet
    to_invalidate, to_remove = dao.get_non_validated_entities(
        start_introspection_time)
    for entity in to_invalidate:
        entity.removed = True
    dao.store_entities(to_invalidate)
    for entity in to_remove:
        dao.remove_entity(entity.__class__, entity.id)

    ## Populate events
    if load_xml_events:
        read_events(event_folders)

    if not TvbProfile.is_first_run():
        ## Create default users.
        if is_db_empty:
            dao.store_entity(
                model.User(TvbProfile.current.web.admin.SYSTEM_USER_NAME, None,
                           None, True, None))
            UserService().create_user(
                username=TvbProfile.current.web.admin.ADMINISTRATOR_NAME,
                password=TvbProfile.current.web.admin.ADMINISTRATOR_PASSWORD,
                email=TvbProfile.current.web.admin.ADMINISTRATOR_EMAIL,
                role=model.ROLE_ADMINISTRATOR)

        ## In case actions related to latest code-changes are needed, make sure they are executed.
        CodeUpdateManager().run_all_updates()

        ## In case the H5 version changed, run updates on all DataTypes
        if TvbProfile.current.version.DATA_CHECKED_TO_VERSION < TvbProfile.current.version.DATA_VERSION:
            thread = threading.Thread(
                target=FilesUpdateManager().run_all_updates)
            thread.start()

        ## Clean tvb-first-time-run temporary folder, as we are no longer at the first run:
        shutil.rmtree(TvbProfile.current.FIRST_RUN_STORAGE, True)
Пример #4
0
 def deco(*a, **b):
     if hasattr(cherrypy, common.KEY_SESSION):
         user = common.get_logged_user()
         if user is not None and user.is_administrator(
         ) or TvbProfile.is_first_run():
             return func(*a, **b)
     raise common.NotAuthenticated(
         'Only Administrators can access this application area!',
         redirect_url='/tvb')
Пример #5
0
def initialize(introspected_modules, load_xml_events=True):
    """
    Initialize when Application is starting.
    Check for new algorithms or new DataTypes.
    """
    SettingsService().check_db_url(TvbProfile.current.db.DB_URL)
    
    ## Initialize DB
    is_db_empty = initialize_startup()
    
    ## Create Projects storage root in case it does not exist.
    initialize_storage()
    
    ## Populate DB algorithms, by introspection
    event_folders = []
    start_introspection_time = datetime.datetime.now()
    for module in introspected_modules:
        introspector = Introspector(module)
        # Introspection is always done, even if DB was not empty.
        introspector.introspect(True)
        event_path = introspector.get_events_path()
        if event_path:
            event_folders.append(event_path)

    # Now remove or mark as removed any unverified Algo-Group, Algo-Category or Portlet
    to_invalidate, to_remove = dao.get_non_validated_entities(start_introspection_time)
    for entity in to_invalidate:
        entity.removed = True
    dao.store_entities(to_invalidate)
    for entity in to_remove:
        dao.remove_entity(entity.__class__, entity.id)
   
    ## Populate events
    if load_xml_events:
        read_events(event_folders)

    if not TvbProfile.is_first_run():
        ## Create default users.
        if is_db_empty:
            dao.store_entity(model.User(TvbProfile.current.web.admin.SYSTEM_USER_NAME, None, None, True, None))
            UserService().create_user(username=TvbProfile.current.web.admin.ADMINISTRATOR_NAME,
                                      password=TvbProfile.current.web.admin.ADMINISTRATOR_PASSWORD,
                                      email=TvbProfile.current.web.admin.ADMINISTRATOR_EMAIL,
                                      role=model.ROLE_ADMINISTRATOR)
        
        ## In case actions related to latest code-changes are needed, make sure they are executed.
        CodeUpdateManager().run_all_updates()

        ## In case the H5 version changed, run updates on all DataTypes
        if TvbProfile.current.version.DATA_CHECKED_TO_VERSION < TvbProfile.current.version.DATA_VERSION:
            thread = threading.Thread(target=FilesUpdateManager().run_all_updates)
            thread.start()

        ## Clean tvb-first-time-run temporary folder, as we are no longer at the first run:
        shutil.rmtree(TvbProfile.current.FIRST_RUN_STORAGE, True)
Пример #6
0
    def test_first_run_save(self):
        """
        Check that before setting something, all flags are pointing towards empty.
        After storing some configurations, check that flags are changed.
        """
        initial_configurations = self.settings_service.configurable_keys
        first_run = TvbProfile.is_first_run()
        assert first_run, "Invalid First_Run flag!!"
        assert not os.path.exists(TEST_CONFIG_FILE)
        assert len(TvbProfile.current.manager.stored_settings) == 0

        to_store_data = {key: value['value'] for key, value in initial_configurations.iteritems()}
        for key, value in self.TEST_SETTINGS.iteritems():
            to_store_data[key] = value
        _, shoud_reset = self.settings_service.save_settings(**to_store_data)

        assert shoud_reset
        first_run = TvbProfile.is_first_run()
        assert not first_run, "Invalid First_Run flag!!"
        assert os.path.exists(TEST_CONFIG_FILE)
        assert not len(TvbProfile.current.manager.stored_settings) == 0
Пример #7
0
    def test_first_run_save(self):
        """
        Check that before setting something, all flags are pointing towards empty.
        After storing some configurations, check that flags are changed.
        """
        initial_configurations = self.settings_service.configurable_keys
        first_run = TvbProfile.is_first_run()
        assert first_run, "Invalid First_Run flag!!"
        assert not os.path.exists(TEST_CONFIG_FILE)
        assert len(TvbProfile.current.manager.stored_settings) == 0

        to_store_data = {key: value['value'] for key, value in initial_configurations.items()}
        for key, value in self.TEST_SETTINGS.items():
            to_store_data[key] = value
        _, shoud_reset = self.settings_service.save_settings(**to_store_data)

        assert shoud_reset
        first_run = TvbProfile.is_first_run()
        assert not first_run, "Invalid First_Run flag!!"
        assert os.path.exists(TEST_CONFIG_FILE)
        assert not len(TvbProfile.current.manager.stored_settings) == 0
    def __init__(self):
        self.logger = get_logger(__name__)
        first_run = TvbProfile.is_first_run()
        storage = TvbProfile.current.TVB_STORAGE if not first_run else TvbProfile.current.DEFAULT_STORAGE
        self.configurable_keys = {
            self.KEY_STORAGE: {'label': 'Root folder for all projects', 'value': storage,
                               'readonly': not first_run, 'type': 'text'},
            self.KEY_MAX_DISK_SPACE_USR: {'label': 'Max hard disk space per user (MBytes)',
                                          'value': TvbProfile.current.MAX_DISK_SPACE / 2 ** 10, 'type': 'text'},
            self.KEY_MATLAB_EXECUTABLE: {'label': 'Optional Matlab or Octave path', 'type': 'text',
                                         'value': TvbProfile.current.MATLAB_EXECUTABLE or get_matlab_executable() or '',
                                         'description': 'Some analyzers will not be available when '
                                                        'matlab/octave are not found'},
            self.KEY_SELECTED_DB: {'label': 'Select one DB engine', 'value': TvbProfile.current.db.SELECTED_DB,
                                   'type': 'select', 'readonly': not first_run,
                                   'options': TvbProfile.current.db.ACEEPTED_DBS},
            self.KEY_DB_URL: {'label': "DB connection URL",
                              'value': TvbProfile.current.db.ACEEPTED_DBS[TvbProfile.current.db.SELECTED_DB],
                              'type': 'text', 'readonly': TvbProfile.current.db.SELECTED_DB == 'sqlite'},

            self.KEY_PORT: {'label': 'Port to run Cherrypy on',
                            'value': TvbProfile.current.web.SERVER_PORT, 'dtype': 'primitive', 'type': 'text'},
            self.KEY_PORT_MPLH5: {'label': 'Port to run Matplotlib on', 'type': 'text', 'dtype': 'primitive',
                                  'value': TvbProfile.current.web.MPLH5_SERVER_PORT},
            self.KEY_URL_WEB: {'label': 'URL for accessing web',
                               'value': TvbProfile.current.web.BASE_URL, 'type': 'text', 'dtype': 'primitive'},
            self.KEY_URL_MPLH5: {'label': 'URL for accessing MPLH5 visualizers', 'type': 'text',
                                 'value': TvbProfile.current.web.MPLH5_SERVER_URL, 'dtype': 'primitive'},

            self.KEY_MAX_NR_THREADS: {'label': 'Maximum no. of threads for local installations', 'type': 'text',
                                      'value': TvbProfile.current.MAX_THREADS_NUMBER, 'dtype': 'primitive'},
            self.KEY_MAX_RANGE: {'label': 'Maximum no. of operations in one PSE',
                                 'description': "Parameters Space Exploration (PSE) maximum number of operations",
                                 'value': TvbProfile.current.MAX_RANGE_NUMBER, 'type': 'text', 'dtype': 'primitive'},
            self.KEY_MAX_NR_SURFACE_VERTEX: {'label': 'Maximum no. of vertices in a surface',
                                             'type': 'text', 'dtype': 'primitive',
                                             'value': TvbProfile.current.MAX_SURFACE_VERTICES_NUMBER},
            self.KEY_CLUSTER: {'label': 'Deploy on cluster', 'value': TvbProfile.current.cluster.IS_DEPLOY,
                               'description': 'Check this only if on the web-server machine OARSUB command is enabled.',
                               'dtype': 'primitive', 'type': 'boolean'},
            self.KEY_ADMIN_NAME: {'label': 'Administrator User Name',
                                  'value': TvbProfile.current.web.admin.ADMINISTRATOR_NAME,
                                  'type': 'text', 'readonly': not first_run,
                                  'description': ('Password and Email can be edited after first run, '
                                                  'from the profile page directly.')},
            self.KEY_ADMIN_PWD: {'label': 'Password',
                                 'value': TvbProfile.current.web.admin.ADMINISTRATOR_BLANK_PWD if first_run
                                 else TvbProfile.current.web.admin.ADMINISTRATOR_PASSWORD,
                                 'type': 'password', 'readonly': not first_run},
            self.KEY_ADMIN_EMAIL: {'label': 'Administrator Email',
                                   'value': TvbProfile.current.web.admin.ADMINISTRATOR_EMAIL,
                                   'readonly': not first_run, 'type': 'text'}}
Пример #9
0
    def __init__(self):
        self.logger = get_logger(__name__)
        first_run = TvbProfile.is_first_run()
        storage = TvbProfile.current.TVB_STORAGE if not first_run else TvbProfile.current.DEFAULT_STORAGE
        self.configurable_keys = {
            self.KEY_STORAGE: {'label': 'Root folder for all projects', 'value': storage,
                               'readonly': not first_run, 'type': 'text'},
            self.KEY_MAX_DISK_SPACE_USR: {'label': 'Max hard disk space per user (MBytes)',
                                          'value': TvbProfile.current.MAX_DISK_SPACE / 2 ** 10, 'type': 'text'},
            self.KEY_MATLAB_EXECUTABLE: {'label': 'Optional Matlab or Octave path', 'type': 'text',
                                         'value': TvbProfile.current.MATLAB_EXECUTABLE or get_matlab_executable() or '',
                                         'description': 'Some analyzers will not be available when '
                                                        'matlab/octave are not found'},
            self.KEY_SELECTED_DB: {'label': 'Select one DB engine', 'value': TvbProfile.current.db.SELECTED_DB,
                                   'type': 'select', 'readonly': not first_run,
                                   'options': TvbProfile.current.db.ACEEPTED_DBS},
            self.KEY_DB_URL: {'label': "DB connection URL",
                              'value': TvbProfile.current.db.ACEEPTED_DBS[TvbProfile.current.db.SELECTED_DB],
                              'type': 'text', 'readonly': TvbProfile.current.db.SELECTED_DB == 'sqlite'},

            self.KEY_PORT: {'label': 'Port to run Cherrypy on',
                            'value': TvbProfile.current.web.SERVER_PORT, 'dtype': 'primitive', 'type': 'text'},
            self.KEY_PORT_MPLH5: {'label': 'Port to run Matplotlib on', 'type': 'text', 'dtype': 'primitive',
                                  'value': TvbProfile.current.web.MPLH5_SERVER_PORT},
            self.KEY_URL_WEB: {'label': 'URL for accessing web',
                               'value': TvbProfile.current.web.BASE_URL, 'type': 'text', 'dtype': 'primitive'},
            self.KEY_URL_MPLH5: {'label': 'URL for accessing MPLH5 visualizers', 'type': 'text',
                                 'value': TvbProfile.current.web.MPLH5_SERVER_URL, 'dtype': 'primitive'},

            self.KEY_MAX_NR_THREADS: {'label': 'Maximum no. of threads for local installations', 'type': 'text',
                                      'value': TvbProfile.current.MAX_THREADS_NUMBER, 'dtype': 'primitive'},
            self.KEY_MAX_RANGE: {'label': 'Maximum no. of operations in one PSE',
                                 'description': "Parameters Space Exploration (PSE) maximum number of operations",
                                 'value': TvbProfile.current.MAX_RANGE_NUMBER, 'type': 'text', 'dtype': 'primitive'},
            self.KEY_MAX_NR_SURFACE_VERTEX: {'label': 'Maximum no. of vertices in a surface',
                                             'type': 'text', 'dtype': 'primitive',
                                             'value': TvbProfile.current.MAX_SURFACE_VERTICES_NUMBER},
            self.KEY_CLUSTER: {'label': 'Deploy on cluster', 'value': TvbProfile.current.cluster.IS_DEPLOY,
                               'description': 'Check this only if on the web-server machine OARSUB command is enabled.',
                               'dtype': 'primitive', 'type': 'boolean'},
            self.KEY_ADMIN_NAME: {'label': 'Administrator User Name',
                                  'value': TvbProfile.current.web.admin.ADMINISTRATOR_NAME,
                                  'type': 'text', 'readonly': not first_run,
                                  'description': ('Password and Email can be edited after first run, '
                                                  'from the profile page directly.')},
            self.KEY_ADMIN_PWD: {'label': 'Password',
                                 'value': TvbProfile.current.web.admin.ADMINISTRATOR_BLANK_PWD if first_run
                                 else TvbProfile.current.web.admin.ADMINISTRATOR_PASSWORD,
                                 'type': 'password', 'readonly': not first_run},
            self.KEY_ADMIN_EMAIL: {'label': 'Administrator Email',
                                   'value': TvbProfile.current.web.admin.ADMINISTRATOR_EMAIL,
                                   'readonly': not first_run, 'type': 'text'}}
Пример #10
0
    def run_all_updates(self):
        """
        Upgrade the code to current version. 
        Go through all update scripts with lower SVN version than the current running version.
        """
        if TvbProfile.is_first_run():
            ## We've just started with a clean TVB. No need to upgrade anything.
            return

        super(CodeUpdateManager, self).run_all_updates()

        if self.checked_version < self.current_version:
            TvbProfile.current.manager.add_entries_to_config_file(
                {stored.KEY_LAST_CHECKED_CODE_VERSION: TvbProfile.current.version.REVISION_NUMBER})
    def run_all_updates(self):
        """
        Upgrade the code to current version. 
        Go through all update scripts with lower SVN version than the current running version.
        """
        if TvbProfile.is_first_run():
            ## We've just started with a clean TVB. No need to upgrade anything.
            return

        super(CodeUpdateManager, self).run_all_updates()

        if self.checked_version < self.current_version:
            TvbProfile.current.manager.add_entries_to_config_file(
                {stored.KEY_LAST_CHECKED_CODE_VERSION: TvbProfile.current.version.SVN_VERSION})
Пример #12
0
def command_initializer(persist_settings=True, skip_import=False):
    if persist_settings and TvbProfile.is_first_run():
        settings_service = SettingsService()
        settings = {}
        # Save default settings
        for key, setting in settings_service.configurable_keys.items():
            settings[key] = setting['value']
        settings_service.save_settings(**settings)
    TvbProfile.set_profile(TvbProfile.COMMAND_PROFILE)
    # Build new db engine in case DB URL value changed
    new_db_engine = build_db_engine()
    SA_SESSIONMAKER.configure(bind=new_db_engine)

    # Initialize application
    initialize(skip_import)
Пример #13
0
def initialize(skip_import=False, skip_updates=False):
    """
    Initialize when Application is starting.
    Check for new algorithms or new DataTypes.
    """
    SettingsService().check_db_url(TvbProfile.current.db.DB_URL)

    # Initialize DB
    is_db_empty = initialize_startup()

    # Create Projects storage root in case it does not exist.
    initialize_storage()

    # Populate DB algorithms, by introspection
    start_introspection_time = datetime.now()
    # Introspection is always done, even if DB was not empty.
    introspector = Introspector()
    introspector.introspect()

    to_invalidate = dao.get_non_validated_entities(start_introspection_time)
    for entity in to_invalidate:
        entity.removed = True
    dao.store_entities(to_invalidate)

    if not TvbProfile.is_first_run() and not skip_updates:
        # Create default users.
        if is_db_empty:
            dao.store_entity(
                User(TvbProfile.current.web.admin.SYSTEM_USER_NAME, TvbProfile.current.web.admin.SYSTEM_USER_NAME, None,
                     None, True, None))
            UserService().create_user(username=TvbProfile.current.web.admin.ADMINISTRATOR_NAME,
                                      display_name=TvbProfile.current.web.admin.ADMINISTRATOR_DISPLAY_NAME,
                                      password=TvbProfile.current.web.admin.ADMINISTRATOR_PASSWORD,
                                      email=TvbProfile.current.web.admin.ADMINISTRATOR_EMAIL,
                                      role=ROLE_ADMINISTRATOR, skip_import=skip_import)

        # In case actions related to latest code-changes are needed, make sure they are executed.
        CodeUpdateManager().run_all_updates()

        # In case the H5 version changed, run updates on all DataTypes
        thread = None
        if TvbProfile.current.version.DATA_CHECKED_TO_VERSION < TvbProfile.current.version.DATA_VERSION:
            thread = threading.Thread(target=FilesUpdateManager().run_all_updates)
            thread.start()

        # Clean tvb-first-time-run temporary folder, as we are no longer at the first run:
        shutil.rmtree(TvbProfile.current.FIRST_RUN_STORAGE, True)
        return thread
Пример #14
0
from tvb.interfaces.web.controllers.settings_controller import SettingsController
from tvb.interfaces.web.controllers.burst.burst_controller import BurstController
from tvb.interfaces.web.controllers.burst.region_model_parameters_controller import RegionsModelParametersController
from tvb.interfaces.web.controllers.burst.exploration_controller import ParameterExplorationController
from tvb.interfaces.web.controllers.burst.dynamic_model_controller import DynamicModelController
from tvb.interfaces.web.controllers.spatial.base_spatio_temporal_controller import SpatioTemporalController
from tvb.interfaces.web.controllers.spatial.surface_model_parameters_controller import SurfaceModelParametersController
from tvb.interfaces.web.controllers.spatial.region_stimulus_controller import RegionStimulusController
from tvb.interfaces.web.controllers.spatial.surface_stimulus_controller import SurfaceStimulusController
from tvb.interfaces.web.controllers.spatial.local_connectivity_controller import LocalConnectivityController
from tvb.interfaces.web.controllers.burst.noise_configuration_controller import NoiseConfigurationController
from tvb.interfaces.web.controllers.api.simulator_controller import SimulatorController


LOGGER = get_logger('tvb.interfaces.web.run')
CONFIG_EXISTS = not TvbProfile.is_first_run()
PARAM_RESET_DB = "reset"
LOGGER.info("TVB application will be running using encoding: " + sys.getdefaultencoding())


def init_cherrypy(arguments=None):
    #### Mount static folders from modules marked for introspection
    arguments = arguments or []
    CONFIGUER = TvbProfile.current.web.CHERRYPY_CONFIGURATION
    for module in arguments:
        module_inst = __import__(str(module), globals(), locals(), ["__init__"])
        module_path = os.path.dirname(os.path.abspath(module_inst.__file__))
        CONFIGUER["/static_" + str(module)] = {'tools.staticdir.on': True,
                                               'tools.staticdir.dir': '.',
                                               'tools.staticdir.root': module_path}
Пример #15
0
                if isrestart:
                    thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset})
                    thread.start()
                    common.add2session(common.KEY_IS_RESTART, True)
                    common.set_important_message('Please wait until TVB is restarted properly!')
                    raise cherrypy.HTTPRedirect('/tvb')
                # Here we will leave the same settings page to be displayed.
                # It will continue reloading when CherryPy restarts.
            except formencode.Invalid, excep:
                template_specification[common.KEY_ERRORS] = excep.unpack_errors()
            except InvalidSettingsException, excep:
                self.logger.error('Invalid settings!  Exception %s was raised' % (str(excep)))
                common.set_error_message(excep.message)
        template_specification.update({'keys_order': self.settingsservice.KEYS_DISPLAY_ORDER,
                                       'config_data': self.settingsservice.configurable_keys,
                                       common.KEY_FIRST_RUN: TvbProfile.is_first_run()})
        return self.fill_default_attributes(template_specification)


    def _restart_services(self, should_reset):
        """
        Restart CherryPy and Backend.
        """
        mplh5 = TvbProfile.current.web.MPLH5_Server_Thread
        if mplh5 is not None:
            mplh5.shutdown()
            mplh5.server_close()
        else:
            self.logger.warning('For some reason the mplh5 never started.')
        cherrypy.engine.exit()
    def setUp(self):

        self.init(with_data=False)
        self.settings_c = SettingsController()
        self.assertTrue(TvbProfile.is_first_run())
Пример #17
0
 def deco(*a, **b):
     if not TvbProfile.is_first_run():
         return func(*a, **b)
     raise common.NotAllowed('You should first set up tvb',
                             redirect_url='/settings/settings')
    def save_settings(self, **data):
        """
        Check if new settings are correct.  Make necessary changes, then save new data in configuration file.
        
        :returns: two boolean values
                    -there were any changes to the configuration;
                    -a reset should be performed on the TVB relaunch.
        """
        new_storage = data[self.KEY_STORAGE]
        previous_storage = TvbProfile.current.TVB_STORAGE

        new_db = data[self.KEY_SELECTED_DB]
        previous_db = TvbProfile.current.db.SELECTED_DB
        db_changed = new_db != previous_db
        storage_changed = new_storage != previous_storage

        matlab_exec = data[self.KEY_MATLAB_EXECUTABLE]
        if matlab_exec == 'None':
            data[self.KEY_MATLAB_EXECUTABLE] = ''
        # Storage changed but DB didn't, just copy TVB storage to new one.
        if storage_changed and not db_changed:
            if os.path.exists(new_storage):
                if os.access(new_storage, os.W_OK):
                    shutil.rmtree(new_storage)
                else:
                    raise InvalidSettingsException("No Write access on storage folder!!")
            shutil.copytree(previous_storage, new_storage)

        if not os.path.isdir(new_storage):
            os.makedirs(new_storage)
        max_space = data[self.KEY_MAX_DISK_SPACE_USR]
        available_mem_kb = SettingsService.get_disk_free_space(new_storage)
        kb_value = int(max_space) * 2 ** 10
        if not (0 < kb_value < available_mem_kb):
            raise InvalidSettingsException("Not enough disk space. There is a maximum of %d MB available on this disk "
                                           "or partition. Wanted %d" % (available_mem_kb / (2 ** 10), max_space))
        data[self.KEY_MAX_DISK_SPACE_USR] = kb_value

        # Save data to file, all while checking if any data has changed
        first_run = TvbProfile.is_first_run()
        if first_run:
            data[stored.KEY_LAST_CHECKED_FILE_VERSION] = TvbProfile.current.version.DATA_VERSION
            data[stored.KEY_LAST_CHECKED_CODE_VERSION] = TvbProfile.current.version.SVN_VERSION
            file_data = data
            if self.KEY_ADMIN_PWD in data:
                data[self.KEY_ADMIN_PWD] = md5(data[self.KEY_ADMIN_PWD]).hexdigest()
            anything_changed = True
        else:
            file_data = TvbProfile.current.manager.stored_settings
            anything_changed = False
            for key in file_data:
                if key in data and str(data[key]) != str(file_data[key]):
                    anything_changed = True
                    file_data[key] = data[key]
            if db_changed:
                file_data[self.KEY_DB_URL] = TvbProfile.current.db.DB_URL
            for key in data:
                if key not in file_data:
                    anything_changed = True
                    file_data[key] = data[key]
        # Write in file new data
        if anything_changed:
            TvbProfile.current.manager.write_config_data(file_data)
            os.chmod(TvbProfile.current.TVB_CONFIG_FILE, 0o644)
        return anything_changed, first_run or db_changed
Пример #19
0
from tvb.interfaces.web.controllers.project.figure_controller import FigureController
from tvb.interfaces.web.controllers.flow_controller import FlowController
from tvb.interfaces.web.controllers.settings_controller import SettingsController
from tvb.interfaces.web.controllers.burst.region_model_parameters_controller import RegionsModelParametersController
from tvb.interfaces.web.controllers.burst.exploration_controller import ParameterExplorationController
from tvb.interfaces.web.controllers.burst.dynamic_model_controller import DynamicModelController
from tvb.interfaces.web.controllers.spatial.base_spatio_temporal_controller import SpatioTemporalController
from tvb.interfaces.web.controllers.spatial.surface_model_parameters_controller import SurfaceModelParametersController
from tvb.interfaces.web.controllers.spatial.region_stimulus_controller import RegionStimulusController
from tvb.interfaces.web.controllers.spatial.surface_stimulus_controller import SurfaceStimulusController
from tvb.interfaces.web.controllers.spatial.local_connectivity_controller import LocalConnectivityController
from tvb.interfaces.web.controllers.burst.noise_configuration_controller import NoiseConfigurationController
from tvb.interfaces.web.controllers.simulator_controller import SimulatorController

LOGGER = get_logger('tvb.interfaces.web.run')
CONFIG_EXISTS = not TvbProfile.is_first_run()
PARAM_RESET_DB = "reset"
LOGGER.info("TVB application will be running using encoding: " +
            sys.getdefaultencoding())


def init_cherrypy(arguments=None):
    #### Mount static folders from modules marked for introspection
    arguments = arguments or []
    CONFIGUER = TvbProfile.current.web.CHERRYPY_CONFIGURATION
    for module in arguments:
        module_inst = importlib.import_module(str(module))
        module_path = os.path.dirname(os.path.abspath(module_inst.__file__))
        CONFIGUER["/static_" + str(module)] = {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.',
Пример #20
0
    def transactional_setup_method(self):

        self.init(with_data=False)
        self.settings_c = SettingsController()
        assert TvbProfile.is_first_run()
Пример #21
0
    def save_settings(self, **data):
        """
        Check if new settings are correct.  Make necessary changes, then save new data in configuration file.
        
        :returns: two boolean values
                    -there were any changes to the configuration;
                    -a reset should be performed on the TVB relaunch.
        """
        new_storage = data[self.KEY_STORAGE]
        previous_storage = TvbProfile.current.TVB_STORAGE

        new_db = data[self.KEY_SELECTED_DB]
        previous_db = TvbProfile.current.db.SELECTED_DB
        db_changed = new_db != previous_db
        storage_changed = new_storage != previous_storage

        matlab_exec = data[self.KEY_MATLAB_EXECUTABLE]
        if matlab_exec == 'None':
            data[self.KEY_MATLAB_EXECUTABLE] = ''
        #Storage changed but DB didn't, just copy TVB storage to new one.
        if storage_changed and not db_changed:
            if os.path.exists(new_storage):
                if os.access(new_storage, os.W_OK):
                    shutil.rmtree(new_storage)
                else:
                    raise InvalidSettingsException(
                        "No Write access on storage folder!!")
            shutil.copytree(previous_storage, new_storage)

        if not os.path.isdir(new_storage):
            os.makedirs(new_storage)
        max_space = data[self.KEY_MAX_DISK_SPACE_USR]
        available_mem_kb = SettingsService.get_disk_free_space(new_storage)
        kb_value = int(max_space) * 2**10
        if not (0 < kb_value < available_mem_kb):
            raise InvalidSettingsException(
                "Not enough disk space. There is a maximum of %d MB available on this disk "
                "or partition. Wanted %d" % (available_mem_kb /
                                             (2**10), max_space))
        data[self.KEY_MAX_DISK_SPACE_USR] = kb_value

        #Save data to file, all while checking if any data has changed
        first_run = TvbProfile.is_first_run()
        if first_run:
            data[
                stored.
                KEY_LAST_CHECKED_FILE_VERSION] = TvbProfile.current.version.DATA_VERSION
            data[
                stored.
                KEY_LAST_CHECKED_CODE_VERSION] = TvbProfile.current.version.SVN_VERSION
            file_data = data
            if self.KEY_ADMIN_PWD in data:
                data[self.KEY_ADMIN_PWD] = md5(
                    data[self.KEY_ADMIN_PWD]).hexdigest()
            anything_changed = True
        else:
            file_data = TvbProfile.current.manager.stored_settings
            anything_changed = False
            for key in file_data:
                if key in data and str(data[key]) != str(file_data[key]):
                    anything_changed = True
                    file_data[key] = data[key]
            if db_changed:
                file_data[self.KEY_DB_URL] = TvbProfile.current.db.DB_URL
            for key in data:
                if key not in file_data:
                    anything_changed = True
                    file_data[key] = data[key]
        # Write in file new data
        if anything_changed:
            TvbProfile.current.manager.write_config_data(file_data)
            os.chmod(TvbProfile.current.TVB_CONFIG_FILE, 0644)
        return anything_changed, first_run or db_changed
Пример #22
0
                # It will continue reloading when CherryPy restarts.
            except formencode.Invalid, excep:
                template_specification[
                    common.KEY_ERRORS] = excep.unpack_errors()
            except InvalidSettingsException, excep:
                self.logger.error(
                    'Invalid settings!  Exception %s was raised' %
                    (str(excep)))
                common.set_error_message(excep.message)
        template_specification.update({
            'keys_order':
            self.settingsservice.KEYS_DISPLAY_ORDER,
            'config_data':
            self.settingsservice.configurable_keys,
            common.KEY_FIRST_RUN:
            TvbProfile.is_first_run()
        })
        return self.fill_default_attributes(template_specification)

    def _restart_services(self, should_reset):
        """
        Restart CherryPy and Backend.
        """
        mplh5 = TvbProfile.current.web.MPLH5_Server_Thread
        if mplh5 is not None:
            mplh5.shutdown()
            mplh5.server_close()
        else:
            self.logger.warning('For some reason the mplh5 never started.')
        cherrypy.engine.exit()
Пример #23
0
                if isrestart:
                    thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset})
                    thread.start()
                    common.add2session(common.KEY_IS_RESTART, True)
                    common.set_important_message('Please wait until TVB is restarted properly!')
                    raise cherrypy.HTTPRedirect('/tvb')
                # Here we will leave the same settings page to be displayed.
                # It will continue reloading when CherryPy restarts.
            except formencode.Invalid, excep:
                template_specification[common.KEY_ERRORS] = excep.unpack_errors()
            except InvalidSettingsException, excep:
                self.logger.error('Invalid settings!  Exception %s was raised' % (str(excep)))
                common.set_error_message(excep.message)
        template_specification.update({'keys_order': self.settingsservice.KEYS_DISPLAY_ORDER,
                                       'config_data': self.settingsservice.configurable_keys,
                                       common.KEY_FIRST_RUN: TvbProfile.is_first_run()})
        return self.fill_default_attributes(template_specification)


    def _restart_services(self, should_reset):
        """
        Restart CherryPy and Backend.
        """
        mplh5 = TvbProfile.current.web.MPLH5_Server_Thread
        if mplh5 is not None:
            mplh5.shutdown()
            mplh5.server_close()
        else:
            self.logger.warning('For some reason the mplh5 never started.')
        cherrypy.engine.exit()
    def transactional_setup_method(self):

        self.init(with_data=False)
        self.settings_c = SettingsController()
        assert TvbProfile.is_first_run()
Пример #25
0
 def deco(*a, **b):
     if hasattr(cherrypy, common.KEY_SESSION):
         user = common.get_logged_user()
         if user is not None and user.is_administrator() or TvbProfile.is_first_run():
             return func(*a, **b)
     raise common.NotAuthenticated('Only Administrators can access this application area!', redirect_url='/tvb')
Пример #26
0
 def deco(*a, **b):
     if not TvbProfile.is_first_run():
         return func(*a, **b)
     raise common.NotAllowed('You should first set up tvb', redirect_url='/settings/settings')