예제 #1
0
    def create_profile(self):
        """
        Set AiiDA to use the test config dir and create a default profile there

        Warning: the AiiDA dbenv must not be loaded when this is called!
        """
        if is_dbenv_loaded():
            raise FixtureError(
                'AiiDA dbenv can not be loaded while creating a test profile')
        if not self.__is_running_on_test_db:
            self.create_aiida_db()
        from aiida.cmdline.verdilib import setup
        if not self.root_dir:
            self.create_root_dir()
        print(self.root_dir, self.config_dir)
        aiida_cfg.AIIDA_CONFIG_FOLDER = self.config_dir
        backend_settings.AIIDADB_PROFILE = None
        aiida_cfg.create_base_dirs()
        profile_name = 'test_profile'
        setup(profile=profile_name,
              only_config=False,
              non_interactive=True,
              **self.profile)
        aiida_cfg.set_default_profile('verdi', profile_name)
        aiida_cfg.set_default_profile('daemon', profile_name)
        self.__is_running_on_test_profile = True
예제 #2
0
    def profile_setdefault(self, *args):
        from aiida.common.setup import set_default_profile

        valid_processes_strlist = ", ".join("'{}'".format(pr)
                                            for pr in valid_processes)

        if len(args) != 2:
            print >> sys.stderr, ("You have to pass (only) two parameters "
                                  "after 'profile setdefault', the name of")
            print >> sys.stderr, ("the process ({}) and the "
                                  "profile to be set as the default.".format(
                                      valid_processes_strlist))
            sys.exit(1)

        process = args[0]
        if process not in valid_processes:
            print >> sys.stderr, (
                "'{}' is not a valid process. Choose it from "
                "the following list: {}.".format(process,
                                                 valid_processes_strlist))
            sys.exit(1)

        profile = args[1]
        # set default DB profiles
        set_default_profile(process, profile, force_rewrite=True)
예제 #3
0
    def setUpClass(cls, *args, **kwargs):
        """
        Create dummy 5 profiles and set first profile as default profile.
        All tests will run on these dummy profiles.

        :param args: list of arguments
        :param kwargs: list of keyword arguments
        """
        super(TestVerdiProfileSetup, cls).setUpClass()

        import tempfile

        cls._old_aiida_config_folder = None
        cls._new_aiida_config_folder = tempfile.mkdtemp()

        cls._old_aiida_config_folder = aiida_cfg.AIIDA_CONFIG_FOLDER
        aiida_cfg.AIIDA_CONFIG_FOLDER = cls._new_aiida_config_folder
        aiida_cfg.create_base_dirs()

        dummy_profile_list = [
            'dummy_profile1', 'dummy_profile2', 'dummy_profile3',
            'dummy_profile4', 'dummy_profile5'
        ]
        dummy_profile_list = [
            "{}_{}".format(profile_name, get_random_string(4))
            for profile_name in dummy_profile_list
        ]

        for profile_name in dummy_profile_list:
            dummy_profile = {}
            dummy_profile['backend'] = 'django'
            dummy_profile['db_host'] = 'localhost'
            dummy_profile['db_port'] = '5432'
            dummy_profile['email'] = 'dummy@localhost'
            dummy_profile['db_name'] = profile_name
            dummy_profile['db_user'] = '******'
            dummy_profile['db_pass'] = '******'
            dummy_profile[
                'repo'] = aiida_cfg.AIIDA_CONFIG_FOLDER + '/repository_' + profile_name
            aiida_cfg.create_config_noninteractive(profile=profile_name,
                                                   **dummy_profile)

        aiida_cfg.set_default_profile(dummy_profile_list[0],
                                      force_rewrite=True)
        cls.dummy_profile_list = dummy_profile_list
예제 #4
0
    def setUpClass(cls, *args, **kwargs):
        super(TestVerdiDevel, cls).setUpClass()

        cls._old_aiida_config_folder = None
        cls._new_aiida_config_folder = tempfile.mkdtemp()
        cls._old_aiida_config_folder = aiida_cfg.AIIDA_CONFIG_FOLDER

        aiida_cfg.AIIDA_CONFIG_FOLDER = cls._new_aiida_config_folder
        aiida_cfg.create_base_dirs()

        cls.profile_name = 'aiida_dummy_profile_1234'
        cls.dummy_profile = {}
        cls.dummy_profile['backend'] = 'django'
        cls.dummy_profile['db_host'] = 'localhost'
        cls.dummy_profile['db_port'] = '5432'
        cls.dummy_profile['email'] = 'dummy@localhost'
        cls.dummy_profile['db_name'] = cls.profile_name
        cls.dummy_profile['db_user'] = '******'
        cls.dummy_profile['db_pass'] = '******'
        cls.dummy_profile['repo'] = aiida_cfg.AIIDA_CONFIG_FOLDER + '/repository_' + cls.profile_name

        aiida_cfg.create_config_noninteractive(profile=cls.profile_name, **cls.dummy_profile)
        aiida_cfg.set_default_profile(cls.profile_name, force_rewrite=True)
예제 #5
0
def quicksetup(self, profile, email, first_name, last_name, institution,
               backend, db_port, db_user, db_user_pw, db_name, repo,
               set_default, non_interactive):
    '''Set up a sane aiida configuration with as little interaction as possible.'''
    from aiida.common.setup import create_base_dirs, AIIDA_CONFIG_FOLDER
    create_base_dirs()

    aiida_dir = os.path.expanduser(AIIDA_CONFIG_FOLDER)

    # access postgres
    postgres = Postgres(port=db_port,
                        interactive=bool(not non_interactive),
                        quiet=False)
    postgres.set_setup_fail_callback(prompt_db_info)
    success = postgres.determine_setup()
    if not success:
        sys.exit(1)

    # default database name is <profile>_<login-name>
    # this ensures that for profiles named test_... the database will also
    # be named test_...
    import getpass
    osuser = getpass.getuser()
    dbname = db_name or profile + '_' + osuser

    # default database user name is aiida_qs_<login-name>
    # default password is random
    dbuser = db_user or 'aiida_qs_' + osuser
    from aiida.common.setup import generate_random_secret_key
    dbpass = db_user_pw or generate_random_secret_key()

    # check if there is a profile that contains the db user already
    # and if yes, take the db user password from there
    # This is ok because a user can only see his own config files
    from aiida.common.setup import (set_default_profile, get_or_create_config)
    confs = get_or_create_config()
    profs = confs.get('profiles', {})
    for v in profs.itervalues():
        if v.get('AIIDADB_USER', '') == dbuser and not db_user_pw:
            dbpass = v.get('AIIDADB_PASS')
            print 'using found password for {}'.format(dbuser)
            break

    try:
        create = True
        if not postgres.dbuser_exists(dbuser):
            postgres.create_dbuser(dbuser, dbpass)
        else:
            dbname, create = _check_db_name(dbname, postgres)
        if create:
            postgres.create_db(dbuser, dbname)
    except Exception as e:
        click.echo('\n'.join([
            'Oops! Something went wrong while creating the database for you.',
            'You may continue with the quicksetup, however:',
            'For aiida to work correctly you will have to do that yourself as follows.',
            manual_setup_instructions(dbuser=dbuser, dbname=dbname), '',
            'Or setup your (OS-level) user to have permissions to create databases and rerun quicksetup.',
            ''
        ]))
        raise e

    # create a profile, by default 'quicksetup' and prompt the user if
    # already exists
    confs = get_or_create_config()
    profile_name = profile or 'quicksetup'
    write_profile = False
    while not write_profile:
        if profile_name in confs.get('profiles', {}):
            if click.confirm(
                    'overwrite existing profile {}?'.format(profile_name)):
                write_profile = True
            else:
                profile_name = click.prompt('new profile name', type=str)
        else:
            write_profile = True

    dbhost = postgres.dbinfo.get('host', 'localhost')
    dbport = postgres.dbinfo.get('port', '5432')

    from os.path import isabs
    repo = repo or 'repository-{}/'.format(profile_name)
    if not isabs(repo):
        repo = os.path.join(aiida_dir, repo)

    setup_args = {
        'backend': backend,
        'email': email,
        'db_host': dbhost,
        'db_port': dbport,
        'db_name': dbname,
        'db_user': dbuser,
        'db_pass': dbpass,
        'repo': repo,
        'first_name': first_name,
        'last_name': last_name,
        'institution': institution,
        'force_overwrite': write_profile,
    }
    setup(profile_name, only_config=False, non_interactive=True, **setup_args)

    # Loop over all valid processes and check if a default profile is set for them
    # If not set the newly created profile as default, otherwise prompt whether to override
    from aiida.cmdline.commands.profile import valid_processes

    default_profiles = confs.get('default_profiles', {})

    for process in valid_processes:

        # if the user specifies whether to override that's fine
        if set_default in [True, False]:
            _set_default = set_default
        # otherwise we may need to ask
        else:
            default_profile = default_profiles.get(process, '')
            if default_profile:
                _set_default = click.confirm(
                    "The default profile for the '{}' process is set to '{}': "
                    "do you want to set the newly created '{}' as the new default? (can be reverted later)"
                    .format(process, default_profile, profile_name))
            # if there are no other default profiles, we don't need to ask
            else:
                _set_default = True

        if _set_default:
            set_default_profile(process, profile_name, force_rewrite=True)
예제 #6
0
def setup(profile, only_config, non_interactive=False, **kwargs):
    '''
    setup an aiida profile and aiida user (and the aiida default user).

    :param profile: Profile name
    :param only_config: do not create a new user
    :param non_interactive: do not prompt for configuration values, fail if not all values are given as kwargs.
    :param backend: one of 'django', 'sqlalchemy'
    :param email: valid email address for the user
    :param db_host: hostname for the database
    :param db_port: port to connect to the database
    :param db_user: name of the db user
    :param db_pass: password of the db user
    '''
    from aiida.common.setup import (create_base_dirs, create_configuration,
                                    set_default_profile, DEFAULT_UMASK,
                                    create_config_noninteractive)
    from aiida.backends.profile import BACKEND_SQLA, BACKEND_DJANGO
    from aiida.backends.utils import set_backend_type
    from aiida.common.exceptions import InvalidOperation

    # ~ cmdline_args = list(args)

    # ~ only_user_config = False
    # ~ try:
    # ~ cmdline_args.remove('--only-config')
    # ~ only_user_config = True
    # ~ except ValueError:
    # ~ # Parameter not provided
    # ~ pass
    only_user_config = only_config

    # ~ if cmdline_args:
    # ~ print >> sys.stderr, "Unknown parameters on the command line: "
    # ~ print >> sys.stderr, ", ".join(cmdline_args)
    # ~ sys.exit(1)

    # create the directories to store the configuration files
    create_base_dirs()
    # gprofile = 'default' if profile is None else profile
    # ~ gprofile = profile if settings_profile.AIIDADB_PROFILE is None \
    # ~ else settings_profile.AIIDADB_PROFILE
    if settings_profile.AIIDADB_PROFILE and profile:
        sys.exit(
            'the profile argument cannot be used if verdi is called with -p option: {} and {}'
            .format(settings_profile.AIIDADB_PROFILE, profile))
    gprofile = settings_profile.AIIDADB_PROFILE or profile
    if gprofile == profile:
        settings_profile.AIIDADB_PROFILE = profile
    if not settings_profile.AIIDADB_PROFILE:
        settings_profile.AIIDADB_PROFILE = 'default'

    # used internally later
    gprofile = settings_profile.AIIDADB_PROFILE

    created_conf = None
    # ask and store the configuration of the DB
    if non_interactive:
        try:
            created_conf = create_config_noninteractive(
                profile=gprofile,
                backend=kwargs['backend'],
                email=kwargs['email'],
                db_host=kwargs['db_host'],
                db_port=kwargs['db_port'],
                db_name=kwargs['db_name'],
                db_user=kwargs['db_user'],
                db_pass=kwargs.get('db_pass', ''),
                repo=kwargs['repo'],
                force_overwrite=kwargs.get('force_overwrite', False))
        except ValueError as e:
            click.echo("Error during configuation: {}".format(e.message),
                       err=True)
            sys.exit(1)
        except KeyError as e:
            click.echo(
                "--non-interactive requires all values to be given on the commandline! Missing argument: {}"
                .format(e.message),
                err=True)
            sys.exit(1)
    else:
        try:
            created_conf = create_configuration(profile=gprofile)
        except ValueError as e:
            print >> sys.stderr, "Error during configuration: {}".format(
                e.message)
            sys.exit(1)

        # set default DB profiles
        set_default_profile('verdi', gprofile, force_rewrite=False)
        set_default_profile('daemon', gprofile, force_rewrite=False)

    if only_user_config:
        print(
            "Only user configuration requested, "
            "skipping the migrate command")
    else:
        print "Executing now a migrate command..."

        backend_choice = created_conf['AIIDADB_BACKEND']
        if backend_choice == BACKEND_DJANGO:
            print("...for Django backend")
            # The correct profile is selected within load_dbenv.
            # Setting os.umask here since sqlite database gets created in
            # this step.
            old_umask = os.umask(DEFAULT_UMASK)

            # This check should be done more properly
            # try:
            #     backend_type = get_backend_type()
            # except KeyError:
            #     backend_type = None
            #
            # if backend_type is not None and backend_type != BACKEND_DJANGO:
            #     raise InvalidOperation("An already existing database found"
            #                            "and a different than the selected"
            #                            "backend was used for its "
            #                            "management.")

            try:
                pass_to_django_manage([execname, 'migrate'], profile=gprofile)
            finally:
                os.umask(old_umask)

            set_backend_type(BACKEND_DJANGO)

        elif backend_choice == BACKEND_SQLA:
            print("...for SQLAlchemy backend")
            from aiida import is_dbenv_loaded
            from aiida.backends import settings
            from aiida.backends.sqlalchemy.utils import (
                _load_dbenv_noschemacheck, check_schema_version)
            from aiida.backends.profile import load_profile

            # We avoid calling load_dbenv since we want to force the schema
            # migration
            if not is_dbenv_loaded():
                settings.LOAD_DBENV_CALLED = True
                # This is going to set global variables in settings, including
                # settings.BACKEND
                load_profile()
                _load_dbenv_noschemacheck()

            # Perform the needed migration quietly
            check_schema_version(force_migration=True)
            set_backend_type(BACKEND_SQLA)

        else:
            raise InvalidOperation("Not supported backend selected.")

    print "Database was created successfully"

    # I create here the default user
    print "Loading new environment..."
    if only_user_config:
        from aiida.backends.utils import load_dbenv, is_dbenv_loaded
        # db environment has not been loaded in this case
        if not is_dbenv_loaded():
            load_dbenv()

    from aiida.common.setup import DEFAULT_AIIDA_USER
    from aiida.orm.user import User as AiiDAUser

    if not AiiDAUser.search_for_users(email=DEFAULT_AIIDA_USER):
        print "Installing default AiiDA user..."
        nuser = AiiDAUser(email=DEFAULT_AIIDA_USER)
        nuser.first_name = "AiiDA"
        nuser.last_name = "Daemon"
        nuser.is_staff = True
        nuser.is_active = True
        nuser.is_superuser = True
        nuser.force_save()

    from aiida.common.utils import get_configured_user_email
    email = get_configured_user_email()
    print "Starting user configuration for {}...".format(email)
    if email == DEFAULT_AIIDA_USER:
        print "You set up AiiDA using the default Daemon email ({}),".format(
            email)
        print "therefore no further user configuration will be asked."
    else:
        # Ask to configure the new user
        if not non_interactive:
            user.configure.main(args=[email])
        else:
            # or don't ask
            aiida.cmdline.commands.user.do_configure(
                email=kwargs['email'],
                first_name=kwargs.get('first_name'),
                last_name=kwargs.get('last_name'),
                institution=kwargs.get('institution'),
                no_password=True,
                non_interactive=non_interactive,
                force=True)

    print "Setup finished."
예제 #7
0
    def _quicksetup_cmd(self, email, first_name, last_name, institution,
                        backend, db_port, db_user, db_user_pw, db_name,
                        profile, repo):
        '''setup a sane aiida configuration with as little interaction as possible.'''
        from aiida.common.setup import create_base_dirs, AIIDA_CONFIG_FOLDER
        create_base_dirs()

        aiida_dir = os.path.expanduser(AIIDA_CONFIG_FOLDER)

        # access postgres
        pg_info = self._get_pg_access()
        pg_execute = pg_info['method']
        dbinfo = pg_info['dbinfo']

        # check if a database setup already exists
        # otherwise setup the database user aiida
        # setup the database aiida_qs_<username>
        from getpass import getuser
        from aiida.common.setup import generate_random_secret_key
        osuser = getuser()
        dbuser = db_user or 'aiida_qs_' + osuser
        dbpass = db_user_pw or generate_random_secret_key()
        dbname = db_name or 'aiidadb_qs_' + osuser

        # check if there is a profile that contains the db user already
        # and if yes, take the db user password from there
        # This is ok because a user can only see his own config files
        from aiida.common.setup import (set_default_profile,
                                        get_or_create_config)
        confs = get_or_create_config()
        profs = confs.get('profiles', {})
        for v in profs.itervalues():
            if v.get('AIIDADB_USER', '') == dbuser and not db_user_pw:
                dbpass = v.get('AIIDADB_PASS')
                print 'using found password for {}'.format(dbuser)
                break

        try:
            create = True
            if not self._dbuser_exists(dbuser, pg_execute, **dbinfo):
                self._create_dbuser(dbuser, dbpass, pg_execute, **dbinfo)
            else:
                dbname, create = self._check_db_name(dbname, pg_execute,
                                                     **dbinfo)
            if create:
                self._create_db(dbuser, dbname, pg_execute, **dbinfo)
        except Exception as e:
            click.echo('\n'.join([
                'Oops! Something went wrong while creating the database for you.',
                'You may continue with the quicksetup, however:',
                'For aiida to work correctly you will have to do that yourself as follows.',
                'Please run the following commands as the user for PostgreSQL (Ubuntu: $sudo su postgres):',
                '', '\t$ psql template1',
                '\t==> ' + self._create_user_command.format(dbuser, dbpass),
                '\t==> ' + self._create_db_command.format(dbname, dbuser),
                '\t==> ' + self._grant_priv_command.format(dbname, dbuser), '',
                'Or setup your (OS-level) user to have permissions to create databases and rerun quicksetup.',
                ''
            ]))
            raise e

        # create a profile, by default 'quicksetup' and prompt the user if
        # already exists
        profile_name = profile or 'quicksetup'
        write_profile = False
        confs = get_or_create_config()
        profile_name = profile or 'quicksetup'
        write_profile = False
        while not write_profile:
            if profile_name in confs.get('profiles', {}):
                if click.confirm(
                        'overwrite existing profile {}?'.format(profile_name)):
                    write_profile = True
                else:
                    profile_name = click.prompt('new profile name', type=str)
            else:
                write_profile = True

        dbhost = dbinfo.get('host', 'localhost')
        dbport = dbinfo.get('port', '5432')

        from os.path import isabs
        repo = repo or 'repository-{}/'.format(profile_name)
        if not isabs(repo):
            repo = os.path.join(aiida_dir, repo)

        setup_args = {
            'backend': backend,
            'email': email,
            'db_host': dbhost,
            'db_port': dbport,
            'db_name': dbname,
            'db_user': dbuser,
            'db_pass': dbpass,
            'repo': repo,
            'first_name': first_name,
            'last_name': last_name,
            'institution': institution,
            'force_overwrite': write_profile,
        }
        setup(profile_name,
              only_config=False,
              non_interactive=True,
              **setup_args)

        # Loop over all valid processes and check if a default profile is set for them
        # If not set the newly created profile as default, otherwise prompt whether to override
        from aiida.cmdline.commands.profile import valid_processes

        default_profiles = confs.get('default_profiles', {})

        for process in valid_processes:

            default_profile = default_profiles.get(process, '')
            default_override = False

            if default_profile:
                default_override = click.confirm(
                    "The default profile for the '{}' process is set to '{}': "
                    "do you want to set the newly created '{}' as the new default? (can be reverted later)"
                    .format(process, default_profile, profile_name))

            if not default_profile or default_override:
                set_default_profile(process, profile_name, force_rewrite=True)
예제 #8
0
def setup_profile(profile,
                  only_config,
                  set_default=False,
                  non_interactive=False,
                  **kwargs):
    """
    Setup an AiiDA profile and AiiDA user (and the AiiDA default user).

    :param profile: Profile name
    :param only_config: do not create a new user
    :param set_default: set the new profile as the default
    :param non_interactive: do not prompt for configuration values, fail if not all values are given as kwargs.
    :param backend: one of 'django', 'sqlalchemy'
    :param email: valid email address for the user
    :param db_host: hostname for the database
    :param db_port: port to connect to the database
    :param db_user: name of the db user
    :param db_pass: password of the db user
    """
    from aiida.backends import settings
    from aiida.backends.profile import BACKEND_SQLA, BACKEND_DJANGO
    from aiida.backends.utils import set_backend_type
    from aiida.cmdline import EXECNAME
    from aiida.cmdline.commands import cmd_user
    from aiida.common.exceptions import InvalidOperation
    from aiida.common.setup import (create_base_dirs, create_configuration,
                                    set_default_profile, DEFAULT_UMASK,
                                    create_config_noninteractive)

    only_user_config = only_config

    # Create the directories to store the configuration files
    create_base_dirs()
    if settings.AIIDADB_PROFILE and profile:
        sys.exit(
            'the profile argument cannot be used if verdi is called with -p option: {} and {}'
            .format(settings.AIIDADB_PROFILE, profile))
    gprofile = settings.AIIDADB_PROFILE or profile
    if gprofile == profile:
        settings.AIIDADB_PROFILE = profile
    if not settings.AIIDADB_PROFILE:
        settings.AIIDADB_PROFILE = 'default'

    # used internally later
    gprofile = settings.AIIDADB_PROFILE

    created_conf = None
    # ask and store the configuration of the DB
    if non_interactive:
        try:
            created_conf = create_config_noninteractive(
                profile=gprofile,
                backend=kwargs['backend'],
                email=kwargs['email'],
                db_host=kwargs['db_host'],
                db_port=kwargs['db_port'],
                db_name=kwargs['db_name'],
                db_user=kwargs['db_user'],
                db_pass=kwargs.get('db_pass', ''),
                repo=kwargs['repo'],
                force_overwrite=kwargs.get('force_overwrite', False))
        except ValueError as exception:
            click.echo("Error during configuation: {}".format(
                exception.message),
                       err=True)
            sys.exit(1)
        except KeyError as exception:
            import traceback
            click.echo(traceback.format_exc())
            click.echo(
                "--non-interactive requires all values to be given on the commandline! Missing argument: {}"
                .format(exception.message),
                err=True)
            sys.exit(1)
    else:
        try:
            created_conf = create_configuration(profile=gprofile)
        except ValueError as exception:
            print >> sys.stderr, "Error during configuration: {}".format(
                exception.message)
            sys.exit(1)

        # Set default DB profile
        set_default_profile(gprofile, force_rewrite=False)

    if only_user_config:
        print("Only user configuration requested, "
              "skipping the migrate command")
    else:
        print("Executing now a migrate command...")

        backend_choice = created_conf['AIIDADB_BACKEND']
        if backend_choice == BACKEND_DJANGO:
            print("...for Django backend")
            # The correct profile is selected within load_dbenv.
            # Setting os.umask here since sqlite database gets created in
            # this step.
            old_umask = os.umask(DEFAULT_UMASK)

            # This check should be done more properly
            # try:
            #     backend_type = get_backend_type()
            # except KeyError:
            #     backend_type = None
            #
            # if backend_type is not None and backend_type != BACKEND_DJANGO:
            #     raise InvalidOperation("An already existing database found"
            #                            "and a different than the selected"
            #                            "backend was used for its "
            #                            "management.")

            try:
                from aiida.backends.djsite.utils import pass_to_django_manage
                pass_to_django_manage([EXECNAME, 'migrate'], profile=gprofile)
            finally:
                os.umask(old_umask)

            set_backend_type(BACKEND_DJANGO)

        elif backend_choice == BACKEND_SQLA:
            print("...for SQLAlchemy backend")
            from aiida import is_dbenv_loaded
            from aiida.backends.sqlalchemy.utils import _load_dbenv_noschemacheck, check_schema_version
            from aiida.backends.profile import load_profile

            # We avoid calling load_dbenv since we want to force the schema
            # migration
            if not is_dbenv_loaded():
                settings.LOAD_DBENV_CALLED = True
                # This is going to set global variables in settings, including settings.BACKEND
                load_profile()
                _load_dbenv_noschemacheck()

            # Perform the needed migration quietly
            check_schema_version(force_migration=True)
            set_backend_type(BACKEND_SQLA)

        else:
            raise InvalidOperation("Not supported backend selected.")

    print("Database was created successfully")

    # I create here the default user
    print("Loading new environment...")
    if only_user_config:
        from aiida.backends.utils import load_dbenv, is_dbenv_loaded
        # db environment has not been loaded in this case
        if not is_dbenv_loaded():
            load_dbenv()

    from aiida.common.setup import DEFAULT_AIIDA_USER
    from aiida.orm.backend import construct_backend

    backend = construct_backend()
    if not backend.users.find(email=DEFAULT_AIIDA_USER):
        print("Installing default AiiDA user...")
        nuser = backend.users.create(email=DEFAULT_AIIDA_USER,
                                     first_name="AiiDA",
                                     last_name="Daemon")
        nuser.is_active = True
        nuser.store()

    from aiida.common.utils import get_configured_user_email
    email = get_configured_user_email()
    print("Starting user configuration for {}...".format(email))
    if email == DEFAULT_AIIDA_USER:
        print("You set up AiiDA using the default Daemon email ({}),".format(
            email))
        print("therefore no further user configuration will be asked.")
    else:
        if non_interactive:
            # Here we map the keyword arguments onto the command line arguments
            # for verdi user configure.  We have to be careful that there the
            # argument names are the same as those int he kwargs dict
            commands = [kwargs['email'], '--non-interactive']

            for arg in ('first_name', 'last_name', 'institution'):
                value = kwargs.get(arg, None)
                if value is not None:
                    commands.extend(
                        ('--{}'.format(arg.replace('_', '-')), str(value)))
        else:
            commands = [email]

        # Ask to configure the user
        try:
            # pylint: disable=no-value-for-parameter
            cmd_user.configure(commands)
        except SystemExit:
            # Have to catch this as the configure command will do a sys.exit()
            pass

    if set_default:
        set_default_profile(profile, force_rewrite=True)

    print("Setup finished.")
예제 #9
0
def profile_setdefault(profile_name):
    """
    Set the passed profile as default profile in aiida config file.
    """
    from aiida.common.setup import set_default_profile
    set_default_profile(profile_name, force_rewrite=True)
예제 #10
0
    def run(self, *args):
        from aiida.common.setup import (create_base_dirs, create_configuration,
                                        set_default_profile, DEFAULT_UMASK)
        from aiida.backends.profile import BACKEND_SQLA, BACKEND_DJANGO
        from aiida.backends.utils import set_backend_type, get_backend_type
        from aiida.common.exceptions import InvalidOperation

        cmdline_args = list(args)

        only_user_config = False
        try:
            cmdline_args.remove('--only-config')
            only_user_config = True
        except ValueError:
            # Parameter not provided
            pass

        if cmdline_args:
            print >> sys.stderr, "Unknown parameters on the command line: "
            print >> sys.stderr, ", ".join(cmdline_args)
            sys.exit(1)

        # create the directories to store the configuration files
        create_base_dirs()
        # gprofile = 'default' if profile is None else profile
        gprofile = 'default' if settings_profile.AIIDADB_PROFILE is None \
            else settings_profile.AIIDADB_PROFILE

        created_conf = None
        # ask and store the configuration of the DB
        try:
            created_conf = create_configuration(profile=gprofile)
        except ValueError as e:
            print >> sys.stderr, "Error during configuration: {}".format(
                e.message)
            sys.exit(1)

        # set default DB profiles
        set_default_profile('verdi', gprofile, force_rewrite=False)
        set_default_profile('daemon', gprofile, force_rewrite=False)

        if only_user_config:
            print(
                "Only user configuration requested, "
                "skipping the migrate command")
        else:
            print "Executing now a migrate command..."

            backend_choice = created_conf['AIIDADB_BACKEND']
            if backend_choice == BACKEND_DJANGO:
                print("...for Django backend")
                # The correct profile is selected within load_dbenv.
                # Setting os.umask here since sqlite database gets created in
                # this step.
                old_umask = os.umask(DEFAULT_UMASK)

                # This check should be done more properly
                # try:
                #     backend_type = get_backend_type()
                # except KeyError:
                #     backend_type = None
                #
                # if backend_type is not None and backend_type != BACKEND_DJANGO:
                #     raise InvalidOperation("An already existing database found"
                #                            "and a different than the selected"
                #                            "backend was used for its "
                #                            "management.")

                try:
                    pass_to_django_manage([execname, 'migrate'],
                                          profile=gprofile)
                finally:
                    os.umask(old_umask)

                set_backend_type(BACKEND_DJANGO)

            elif backend_choice == BACKEND_SQLA:
                print("...for SQLAlchemy backend")
                from aiida.backends.sqlalchemy.models.base import Base
                from aiida.backends.sqlalchemy.utils import (get_engine,
                                                             install_tc)
                from aiida.common.setup import get_profile_config
                from aiida import is_dbenv_loaded, load_dbenv

                if not is_dbenv_loaded():
                    load_dbenv()

                # This check should be done more properly
                # try:
                #     backend_type = get_backend_type()
                # except KeyError:
                #     backend_type = None
                #
                # if backend_type is not None and backend_type != BACKEND_SQLA:
                #     raise InvalidOperation("An already existing database found"
                #                            "and a different than the selected"
                #                            "backend was used for its "
                #                            "management.")

                # Those import are necessary for SQLAlchemy to correctly create
                # the needed database tables.
                from aiida.backends.sqlalchemy.models.authinfo import (
                    DbAuthInfo)
                from aiida.backends.sqlalchemy.models.comment import DbComment
                from aiida.backends.sqlalchemy.models.computer import (
                    DbComputer)
                from aiida.backends.sqlalchemy.models.group import (
                    DbGroup, table_groups_nodes)
                from aiida.backends.sqlalchemy.models.lock import DbLock
                from aiida.backends.sqlalchemy.models.log import DbLog
                from aiida.backends.sqlalchemy.models.node import (DbLink,
                                                                   DbNode,
                                                                   DbPath,
                                                                   DbCalcState)
                from aiida.backends.sqlalchemy.models.user import DbUser
                from aiida.backends.sqlalchemy.models.workflow import (
                    DbWorkflow, DbWorkflowData, DbWorkflowStep)
                from aiida.backends.sqlalchemy.models.settings import DbSetting

                connection = get_engine(get_profile_config(gprofile))
                Base.metadata.create_all(connection)
                install_tc(connection)

                set_backend_type(BACKEND_SQLA)

            else:
                raise InvalidOperation("Not supported backend selected.")

        print "Database was created successfully"

        # I create here the default user
        print "Loading new environment..."
        if only_user_config:
            from aiida.backends.utils import load_dbenv, is_dbenv_loaded
            # db environment has not been loaded in this case
            if not is_dbenv_loaded():
                load_dbenv()

        from aiida.common.setup import DEFAULT_AIIDA_USER
        from aiida.orm.user import User as AiiDAUser

        if not AiiDAUser.search_for_users(email=DEFAULT_AIIDA_USER):
            print "Installing default AiiDA user..."
            nuser = AiiDAUser(email=DEFAULT_AIIDA_USER)
            nuser.first_name = "AiiDA"
            nuser.last_name = "Daemon"
            nuser.is_staff = True
            nuser.is_active = True
            nuser.is_superuser = True
            nuser.force_save()

        from aiida.common.utils import get_configured_user_email
        email = get_configured_user_email()
        print "Starting user configuration for {}...".format(email)
        if email == DEFAULT_AIIDA_USER:
            print "You set up AiiDA using the default Daemon email ({}),".format(
                email)
            print "therefore no further user configuration will be asked."
        else:
            # Ask to configure the new user
            User().user_configure(email)

        print "Install finished."