def _write_cfg_file(self, initial_data): """ Write in CFG file, a dictionary of properties""" with open(cfg.TVB_CONFIG_FILE, 'w') as file_writer: for key in initial_data: file_writer.write(key + '=' + str(initial_data[key]) + '\n') file_writer.close() cfg.read_config_file() self.settings_service = SettingsService()
def setUp(self): self.initial_settings = {} self.old_config_file = cfg.TVB_CONFIG_FILE cfg.TVB_CONFIG_FILE = TEST_CONFIG_FILE if os.path.exists(cfg.TVB_CONFIG_FILE): os.remove(cfg.TVB_CONFIG_FILE) for key in dir(cfg): self.initial_settings[key] = getattr(cfg, key) self.settings_service = SettingsService()
def setUp(self): """ Sets up the environment for testing; saves config file; creates initial TVB settings and a `SettingsService` """ self.initial_settings = {} self.old_config_file = cfg.TVB_CONFIG_FILE cfg.TVB_CONFIG_FILE = TEST_CONFIG_FILE if os.path.exists(cfg.TVB_CONFIG_FILE): os.remove(cfg.TVB_CONFIG_FILE) for key in dir(cfg): self.initial_settings[key] = getattr(cfg, key) self.settings_service = SettingsService()
def deco(*a, **b): """ Decorator for public method""" if hasattr(cherrypy, basecontroller.KEY_SESSION): user = basecontroller.get_logged_user() if (user is not None and user.is_administrator() ) or SettingsService.is_first_run(): return func(*a, **b) basecontroller.set_error_message( 'Only Administrators can access this application area!') raise cherrypy.HTTPRedirect('/tvb')
def initialize(introspected_modules, load_xml_events=True): """ Initialize when Application is starting. Check for new algorithms or new DataTypes. """ SettingsService().check_db_url(cfg.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 any unverified Algo-Groups, categories or Portlets invalid_stored_entities = dao.get_non_validated_entities( start_introspection_time) for entity in invalid_stored_entities: dao.remove_entity(entity.__class__, entity.id) ## Populate events if load_xml_events: eventhandler.read_events(event_folders) ## Make sure DB events are linked. db_events.attach_db_events() ## Create default users. if is_db_empty: dao.store_entity( model.User(cfg.SYSTEM_USER_NAME, None, None, True, None)) UserService().create_user(username=cfg.ADMINISTRATOR_NAME, password=cfg.ADMINISTRATOR_PASSWORD, email=cfg.ADMINISTRATOR_EMAIL, role=ROLE_ADMINISTRATOR) ## In case actions related to latest code-changes are needed, make sure they are executed. CodeUpdateManager().update_all()
def create_user(self, username=None, password=None, password2=None, role=None, email=None, comment=None, email_msg=None, validated=False): """ Service Layer for creating a new user. """ #Basic fields validation. if (username is None) or len(username) < 1: raise UsernameException("Empty UserName!") if (password is None) or len(password) < 1: raise UsernameException("Empty password!") if password2 is None: password2 = password if password != password2: raise UsernameException("Passwords do not match!") try: user_validated = (role == 'ADMINISTRATOR') or validated user = model.User(username, password, email, user_validated, role) if email_msg is None: email_msg = 'Hello ' + username + TEXT_CREATE admin_msg = (TEXT_CREATE_TO_ADMIN + username + ' :\n ' + cfg.BASE_URL + 'user/validate/' + username + '\n\n"' + str(comment) + '"') self.logger.info("Registering user " + username + " !") if role != 'ADMINISTRATOR' and email is not None: admins = UserService.get_administrators() admin = admins[randint(0, len(admins) - 1)] if admin.email is not None and (admin.email != cfg.DEFAULT_ADMIN_EMAIL or cfg.SERVER_IP != cfg.LOCALHOST): #Do not send validation email in case default admin email # remained unchanged but TVB in locally deployed.... emailsender.send(FROM_ADDRESS, admin.email, SUBJECT_REGISTER, admin_msg) self.logger.debug("Email sent to:" + admin.email + " for validating user:"******" !") emailsender.send(FROM_ADDRESS, email, SUBJECT_REGISTER, email_msg) self.logger.debug("Email sent to:" + email + " for notifying new user:"******" !") user = dao.store_entity(user) if not SettingsService.is_first_run(): eventhandler.handle_event(".".join([self.__class__.__name__, stack()[0][3]]), user) return TEXT_DISPLAY except Exception, excep: self.logger.error("Could not create user!") self.logger.exception(excep) raise UsernameException(excep.message)
class SettingsController(UserController): """ Controller for TVB-Settings web page. Inherit from UserController, to have the same fill_default_attributes method (with versionInfo). """ def __init__(self): UserController.__init__(self) self.settingsservice = SettingsService() @cherrypy.expose @using_template('user/base_user') @admin() 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() bc.add2session(bc.KEY_IS_RESTART, True) bc.set_info_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[bc.KEY_ERRORS] = excep.unpack_errors() except InvalidSettingsException, excep: self.logger.error( 'Invalid settings! Exception %s was raised' % (str(excep))) bc.set_error_message(excep.message)
def __init__(self): UserController.__init__(self) self.settingsservice = SettingsService()
from tvb.interfaces.web.controllers.project.projectcontroller import ProjectController from tvb.interfaces.web.controllers.project.figurecontroller import FigureController from tvb.interfaces.web.controllers.project.dtipipelinecontroller import DTIPipelineController from tvb.interfaces.web.controllers.flowcontroller import FlowController from tvb.interfaces.web.controllers.settingscontroller import SettingsController from tvb.interfaces.web.controllers.burst.burstcontroller import BurstController from tvb.interfaces.web.controllers.burst.explorationcontroller import ParameterExplorationController from tvb.interfaces.web.controllers.spatial.base_spatiotemporalcontroller import SpatioTemporalController from tvb.interfaces.web.controllers.spatial.regionsmodelparameterscontroller import RegionsModelParametersController from tvb.interfaces.web.controllers.spatial.surfacemodelparameterscontroller import SurfaceModelParametersController from tvb.interfaces.web.controllers.spatial.regionstimuluscontroller import RegionStimulusController from tvb.interfaces.web.controllers.spatial.surfacestimuluscontroller import SurfaceStimulusController from tvb.interfaces.web.controllers.spatial.localconnectivitycontroller import LocalConnectivityController LOGGER = get_logger('tvb.interface.web.run') CONFIG_EXISTS = not SettingsService.is_first_run() PARAM_RESET_DB = "reset" ### Ensure Python is using UTF-8 encoding. ### While running distribution/console, default encoding is ASCII reload(sys) sys.setdefaultencoding('utf-8') LOGGER.info("TVB application running using encoding: " + sys.getdefaultencoding()) def init_cherrypy(arguments=None): #### Mount static folders from modules marked for introspection arguments = arguments or [] CONFIGUER = TVBSettings.CHERRYPY_CONFIGURATION for module in arguments:
class SettingsServiceTest(unittest.TestCase): """ This class contains tests for the tvb.core.services.settingsservice module. """ def _write_cfg_file(self, initial_data): """ Write in CFG file, a dictionary of properties""" with open(cfg.TVB_CONFIG_FILE, 'w') as file_writer: for key in initial_data: file_writer.write(key + '=' + str(initial_data[key]) + '\n') file_writer.close() cfg.read_config_file() self.settings_service = SettingsService() def setUp(self): """ Sets up the environment for testing; saves config file; creates initial TVB settings and a `SettingsService` """ self.initial_settings = {} self.old_config_file = cfg.TVB_CONFIG_FILE cfg.TVB_CONFIG_FILE = TEST_CONFIG_FILE if os.path.exists(cfg.TVB_CONFIG_FILE): os.remove(cfg.TVB_CONFIG_FILE) for key in dir(cfg): self.initial_settings[key] = getattr(cfg, key) self.settings_service = SettingsService() def tearDown(self): """ Clean up after testing is done; restore config file """ if os.path.exists(cfg.TVB_CONFIG_FILE): os.remove(cfg.TVB_CONFIG_FILE) cfg.FILE_SETTINGS = None cfg.TVB_CONFIG_FILE = self.old_config_file def test_check_db_url_invalid(self): """ Make sure a proper exception is raised in case an invalid database url is passed. """ self.assertRaises(InvalidSettingsException, self.settings_service.check_db_url, "this-url-should-be-invalid") def test_get_free_disk_space(self): """ Check that no unexpected exception is raised during the query for free disk space. Also do a check that returned value is greater than 0. Not most precise check but other does not seem possible so far. """ disk_space = self.settings_service.get_disk_free_space(cfg.TVB_STORAGE) self.assertTrue(disk_space > 0, "Disk space should never be negative.") def test_getsettings_no_configfile(self): """ If getting the interface with no configuration file present, the configurations dictionary should not change and the first_run parameter should be true. """ initial_configurations = self.settings_service.configurable_keys updated = self.settings_service.configurable_keys first_run = self.settings_service.is_first_run() self.assertEqual(initial_configurations, updated, "Configuration changed even with no config file.") self.assertTrue(first_run, "Invalid First_Run flag!!") def test_getsettings_with_config(self): """ Test to see that keys from the configuration dict is updated with the value from the configuration file. """ storage = os.path.join(cfg.TVB_STORAGE, 'test_storage') initial_configurations = self.settings_service.configurable_keys #Simulate the encrypted value is stored initial_configurations[self.settings_service.KEY_ADMIN_PWD] = {'value': cfg.ADMINISTRATOR_PASSWORD} test_dict = {self.settings_service.KEY_ADMIN_NAME: 'test_name', self.settings_service.KEY_ADMIN_EMAIL: '*****@*****.**', self.settings_service.KEY_PORT: 8081, self.settings_service.KEY_IP: "192.168.123.11",} self._write_cfg_file(test_dict) updated_cfg = self.settings_service.configurable_keys isfirst = self.settings_service.is_first_run() self.assertFalse(isfirst, "Invalid First_Run flag!!") for key in updated_cfg: if key in test_dict: self.assertEqual(updated_cfg[key]['value'], test_dict[key]) else: self.assertEqual(updated_cfg[key]['value'], initial_configurations[key]['value']) def test_updatesets_with_config(self): """ Test that the config.py entries are updated accordingly when a configuration file is present. """ test_storage = os.path.join(cfg.TVB_STORAGE, 'test_storage') test_dict = {self.settings_service.KEY_STORAGE: test_storage, self.settings_service.KEY_ADMIN_NAME: 'test_name', self.settings_service.KEY_ADMIN_EMAIL: '*****@*****.**', self.settings_service.KEY_PORT: 8081} old_settings = {} for attr in dir(cfg): if not attr.startswith('__'): old_settings[attr] = getattr(cfg, attr) self._write_cfg_file(test_dict) for attr in dir(cfg): if not attr.startswith('__'): if attr in test_dict: self.assertEqual(test_dict[attr], getattr(cfg, attr), 'For some reason attribute %s did not change'%(attr)) def test_savesettings_no_change(self): """ Test than when nothing changes in the settings file, the correct flags are returned. """ test_storage = os.path.join(cfg.TVB_STORAGE, 'test_storage') disk_storage = 100 initial_data = {self.settings_service.KEY_STORAGE: test_storage, self.settings_service.KEY_ADMIN_NAME: 'test_name', self.settings_service.KEY_SELECTED_DB: cfg.SELECTED_DB, self.settings_service.KEY_DB_URL: cfg.DB_URL, self.settings_service.KEY_ADMIN_EMAIL: '*****@*****.**', self.settings_service.KEY_MAX_DISK_SPACE_USR: disk_storage * (2 ** 10), self.settings_service.KEY_PORT: 8081, self.settings_service.KEY_MATLAB_EXECUTABLE: 'test',} self._write_cfg_file(initial_data) initial_data[self.settings_service.KEY_MAX_DISK_SPACE_USR] = disk_storage changes, restart = self.settings_service.save_settings(**initial_data) self.assertFalse(changes) self.assertFalse(restart) def test_savesettings_changedir(self): """ Test than storage is changed, the data is copied in proper place. """ #Add some additional entries that would normaly come from the UI. old_storage = os.path.join(cfg.TVB_STORAGE, 'tvb_test_old') new_storage = os.path.join(cfg.TVB_STORAGE, 'tvb_test_new') test_data = 'tvb_test_data' if os.path.exists(old_storage): shutil.rmtree(old_storage) os.makedirs(old_storage) file_writer = open(os.path.join(old_storage, test_data), 'w') file_writer.write('test') file_writer.close() initial_data = {self.settings_service.KEY_STORAGE: old_storage, self.settings_service.KEY_ADMIN_NAME: 'test_name', self.settings_service.KEY_SELECTED_DB: cfg.SELECTED_DB, self.settings_service.KEY_DB_URL: cfg.DB_URL, self.settings_service.KEY_MAX_DISK_SPACE_USR: 100, self.settings_service.KEY_MATLAB_EXECUTABLE: 'test'} self._write_cfg_file(initial_data) initial_data[self.settings_service.KEY_STORAGE] = new_storage anything_changed, is_reset = self.settings_service.save_settings(**initial_data) self.assertTrue(anything_changed) self.assertFalse(is_reset) copied_file_path = os.path.join(new_storage, test_data) data = open(copied_file_path, 'r').read() self.assertEqual(data, 'test') shutil.rmtree(old_storage) shutil.rmtree(new_storage)
def deco(*a, **b): """ Decorator for public method""" if not SettingsService.is_first_run(): return func(*a, **b) raise cherrypy.HTTPRedirect('/settings/settings')