Beispiel #1
0
def clear(args):
    print("Deleting all messages with context = {} in database {}".format(
        os.environ["LEAPP_EXECUTION_ID"],
        get_config().get("database", "path")
    ))
    with get_connection(None) as con:
        con.execute("DELETE FROM message WHERE context = ?", (os.environ["LEAPP_EXECUTION_ID"],))
Beispiel #2
0
def test_migrations_are_applied():
    con = sqlite3.connect(get_config().get('database', 'path'))
    con.executescript(_ORIGINAL_DB_SCHEMA)
    assert con.execute("PRAGMA user_version").fetchone()[0] == 0
    con.close()

    with get_connection(None) as db:
        assert db.execute("PRAGMA user_version").fetchone()[0] > 0
Beispiel #3
0
def test_message_data(saved=True):
    e = MessageData(data='abc', hash_id='abc')
    if saved:
        e.store()
        with get_connection(None) as conn:
            data = conn.execute(
                'SELECT data from message_data WHERE hash = "abc"').fetchone()[0]
        assert data == 'abc'
    return e
Beispiel #4
0
def fetch_all_upgrade_contexts():
    """
    :return: All upgrade execution contexts
    """
    with get_connection(None) as db:
        cursor = db.execute(
            "SELECT context, stamp, configuration FROM execution WHERE kind = 'upgrade' ORDER BY id DESC")
        row = cursor.fetchall()
        if row:
            return row
    return None
Beispiel #5
0
def fetch_last_upgrade_context():
    """
    :return: Context of the last execution
    """
    with get_connection(None) as db:
        cursor = db.execute(
            "SELECT context, stamp, configuration FROM execution WHERE kind = 'upgrade' ORDER BY id DESC LIMIT 1")
        row = cursor.fetchone()
        if row:
            return row[0], json.loads(row[2])
    return None, {}
Beispiel #6
0
def clone_context(oldcontext, newcontext, use_db=None):
    # Enter transaction - In case of any exception automatic rollback is issued
    # and it is automatically committed if there was no exception
    with get_connection(use_db) as db:
        # First clone host entries
        host = _dup_host(db=db, newcontext=newcontext, oldcontext=oldcontext)
        # Next clone data_source entries and use the lookup table generated by the host duplication
        data_source = _dup_data_source(db=db, host=host, newcontext=newcontext, oldcontext=oldcontext)
        # Next clone message entries and use the lookup table generated by the data_source duplication
        message = _dup_message(db=db, data_source=data_source, newcontext=newcontext, oldcontext=oldcontext)
        # Last clone message entries and use the lookup table generated by the data_source and message duplications
        _dup_audit(db=db, data_source=data_source, message=message, newcontext=newcontext, oldcontext=oldcontext)
Beispiel #7
0
def fetch_last_upgrade_context():
    """
    :return: Context of the last execution
    """
    with get_connection(None) as db:
        cursor = db.execute(
            "SELECT context, stamp FROM execution WHERE kind = 'upgrade' ORDER BY stamp DESC LIMIT 1"
        )
        row = cursor.fetchone()
        if row:
            return row[0]
    return None
Beispiel #8
0
def rerun(args):

    if os.environ.get('LEAPP_UNSUPPORTED') != '1':
        raise CommandError('This command requires the environment variable LEAPP_UNSUPPORTED="1" to be set!')

    if args.from_phase not in RERUN_SUPPORTED_PHASES:
        raise CommandError('This command is only supported for {}'.format(', '.join(RERUN_SUPPORTED_PHASES)))

    context = str(uuid.uuid4())
    last_context, configuration = util.fetch_last_upgrade_context()
    phases = [chkpt['phase'] for chkpt in util.get_checkpoints(context=last_context)]
    if args.from_phase not in set(phases):
        raise CommandError('Phase {} has not been executed in the last leapp upgrade execution. '
                           'Cannot rerun not executed phase'.format(args.from_phase))

    if not last_context:
        raise CommandError('No previous upgrade run to rerun - '
                           'leapp upgrade has to be run before leapp rerun can be used')

    with get_connection(None) as db:
        e = Execution(context=context, kind='rerun', configuration=configuration)

        e.store(db)

        clone_context(last_context, context, db)
        db.execute('''
            DELETE FROM audit WHERE id IN (
                SELECT
                    audit.id          AS id
                FROM
                    audit
                JOIN
                    data_source ON data_source.id = audit.data_source_id
                WHERE
                    audit.context = ? AND audit.event = 'checkpoint'
                    AND data_source.phase LIKE 'FirstBoot%'
            );
        ''', (context,))
        db.execute('''DELETE FROM message WHERE context = ? and type = 'ErrorModel';''', (context,))

    util.archive_logfiles()
    upgrade(Namespace(  # pylint: disable=no-value-for-parameter
        resume=True,
        resume_context=context,
        only_with_tags=args.only_actors_with_tag or [],
        debug=args.debug,
        verbose=args.verbose,
        reboot=False,
        no_rhsm=False,
        channel=None,
        whitelist_experimental=[],
        enablerepo=[]))
Beispiel #9
0
 def wrapper(*args, **kwargs):
     with get_connection(None) as db:
         cursor = db.execute("""
           SELECT context, stamp FROM execution WHERE kind = 'snactor-run' ORDER BY stamp DESC LIMIT 1
         """)
         row = cursor.fetchone()
         if row:
             context = row[0]
         else:
             context = str(uuid.uuid4())
             Execution(context=context,
                       kind='snactor-run',
                       configuration='').store()
         os.environ["LEAPP_EXECUTION_ID"] = context
     return f(*args, **kwargs)
Beispiel #10
0
def last_snactor_context(connection=None):
    """
    Retrieves the last snactor-run context from the database. It generates a new one if none has been found.

    :param connection: Database connection to use instead of the default connection.
    :returns: String representing the latest snactor-run context uuid.
    """
    with get_connection(db=connection) as db:
        cursor = db.execute('''
            SELECT context, stamp FROM execution WHERE kind = 'snactor-run' ORDER BY id DESC LIMIT 1
        ''')
        row = cursor.fetchone()
        if row:
            context = row[0]
        else:
            context = str(uuid.uuid4())
            Execution(context=context, kind='snactor-run', configuration='').store()
        return context
Beispiel #11
0
def loaded_leapp_repository(request):
    """
    This fixture will ensure that the repository for the current test run is loaded with all its links etc.

    This enables running actors and using models, tags, topics, workflows etc.

    Additionally loaded_leapp_repository gives you access to a :py:class:`leapp.repository.manager.RepositoryManager`
    instance.

    :Example:

    .. code-block:: python

        from leapp.snactor.fixture import loaded_leapp_repository
        from leapp.models import ExampleModel, ProcessedExampleModel

        def my_repository_library_test(loaded_leapp_repository):
            from leapp.libraries.common import global
            e = ExampleModel(value='Some string')
            result = global.process_function(e)
            assert type(result) is ProcessedExampleModel

    """
    repository_path = find_repository_basedir(request.module.__file__)
    os.environ['LEAPP_CONFIG'] = os.path.join(repository_path, '.leapp',
                                              'leapp.conf')
    os.environ['LEAPP_HOSTNAME'] = socket.getfqdn()
    context = str(uuid.uuid4())
    with get_connection(None):
        Execution(context=context, kind='snactor-test-run',
                  configuration='').store()
        os.environ["LEAPP_EXECUTION_ID"] = context

        manager = getattr(request.session, 'leapp_repository', None)
        if not manager:
            manager = find_and_scan_repositories(repository_path,
                                                 include_locals=True)
            manager.load(resolve=True)
        yield manager
Beispiel #12
0
def test_pass_through():
    with get_connection(None) as db:
        with get_connection(db) as db2:
            assert db is db2