Search in sources :

Example 6 with Connection

use of liquibase.hub.model.Connection in project liquibase by liquibase.

the class Liquibase method getConnection.

/**
 * Create or retrieve the Connection object
 *
 * @param   changeLog              Database changelog
 * @return  Connection
 * @throws  LiquibaseHubException  Thrown by HubService
 */
public Connection getConnection(DatabaseChangeLog changeLog) throws LiquibaseHubException {
    // 
    // If our current Executor is a LoggingExecutor then just return since we will not update Hub
    // 
    Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
    if (executor instanceof LoggingExecutor) {
        return null;
    }
    String changeLogId = changeLog.getChangeLogId();
    HubUpdater hubUpdater = new HubUpdater(new Date(), changeLog, database);
    if (hubUpdater.hubIsNotAvailable(changeLogId)) {
        if (StringUtil.isNotEmpty(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue()) && changeLogId == null) {
            String message = "The API key '" + HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue() + "' was found, but no changelog ID exists.\n" + "No operations will be reported. Register this changelog with Liquibase Hub to generate free deployment reports.\n" + "Learn more at https://hub.liquibase.com.";
            Scope.getCurrentScope().getUI().sendMessage("WARNING: " + message);
            Scope.getCurrentScope().getLog(getClass()).warning(message);
        }
        return null;
    }
    // 
    if (StringUtil.isEmpty(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue()) && changeLogId != null) {
        String message = "The changelog ID '" + changeLogId + "' was found, but no API Key exists.\n" + "No operations will be reported. Simply add a liquibase.hub.apiKey setting to generate free deployment reports.\n" + "Learn more at https://hub.liquibase.com.";
        Scope.getCurrentScope().getUI().sendMessage("WARNING: " + message);
        Scope.getCurrentScope().getLog(getClass()).warning(message);
        return null;
    }
    Connection connection;
    final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    if (getHubConnectionId() == null) {
        HubChangeLog hubChangeLog = hubService.getHubChangeLog(UUID.fromString(changeLogId), "*");
        if (hubChangeLog == null) {
            Scope.getCurrentScope().getLog(getClass()).warning("Retrieving Hub Change Log failed for Changelog ID: " + changeLogId);
            return null;
        }
        if (hubChangeLog.isDeleted()) {
            // 
            // Complain and stop the operation
            // 
            String message = "\n" + "The operation did not complete and will not be reported to Hub because the\n" + "" + "registered changelog has been deleted by someone in your organization.\n" + "Learn more at http://hub.liquibase.com.";
            throw new LiquibaseHubException(message);
        }
        Connection exampleConnection = new Connection();
        exampleConnection.setProject(hubChangeLog.getProject());
        exampleConnection.setJdbcUrl(Liquibase.this.database.getConnection().getURL());
        connection = hubService.getConnection(exampleConnection, true);
        setHubConnectionId(connection.getId());
    } else {
        connection = hubService.getConnection(new Connection().setId(getHubConnectionId()), true);
    }
    return connection;
}
Also used : Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) LoggingExecutor(liquibase.executor.LoggingExecutor) HubChangeLog(liquibase.hub.model.HubChangeLog) ExecutorService(liquibase.executor.ExecutorService) DatabaseConnection(liquibase.database.DatabaseConnection) Connection(liquibase.hub.model.Connection)

Example 7 with Connection

use of liquibase.hub.model.Connection in project liquibase by liquibase.

the class Liquibase method update.

/**
 * Update to tag
 *
 * @param   tag                             Tag to update for
 * @param   contexts
 * @param   labelExpression
 * @throws  LiquibaseException
 */
public void update(String tag, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
    if (tag == null) {
        update(contexts, labelExpression);
        return;
    }
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    runInScope(new Scope.ScopedRunner() {

        @Override
        public void run() throws Exception {
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.waitForLock();
            HubUpdater hubUpdater = null;
            Operation updateOperation = null;
            BufferedLogService bufferLog = new BufferedLogService();
            DatabaseChangeLog changeLog = null;
            try {
                changeLog = getDatabaseChangeLog();
                checkLiquibaseTables(true, changeLog, contexts, labelExpression);
                ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
                changeLog.validate(database, contexts, labelExpression);
                // 
                // Let the user know that they can register for Hub
                // 
                hubUpdater = new HubUpdater(new Date(), changeLog, database);
                hubUpdater.register(changeLogFile);
                // 
                // Create an iterator which will be used with a ListVisitor
                // to grab the list of change sets for the update
                // 
                List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
                ChangeLogIterator listLogIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new UpToTagChangeSetFilter(tag, ranChangeSetList));
                // 
                // Create or retrieve the Connection
                // Make sure the Hub is available here by checking the return
                // 
                Connection connection = getConnection(changeLog);
                if (connection != null) {
                    updateOperation = hubUpdater.preUpdateHub("UPDATE", "update-to-tag", connection, changeLogFile, contexts, labelExpression, listLogIterator);
                }
                // 
                if (connection != null) {
                    changeExecListener = new HubChangeExecListener(updateOperation, changeExecListener);
                }
                // 
                // Create another iterator to run
                // 
                ChangeLogIterator runChangeLogIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new UpToTagChangeSetFilter(tag, ranChangeSetList));
                CompositeLogService compositeLogService = new CompositeLogService(true, bufferLog);
                Scope.child(Scope.Attr.logService.name(), compositeLogService, () -> {
                    runChangeLogIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
                });
                hubUpdater.postUpdateHub(updateOperation, bufferLog);
            } catch (Throwable e) {
                if (hubUpdater != null) {
                    hubUpdater.postUpdateHubExceptionHandling(updateOperation, bufferLog, e.getMessage());
                }
                throw e;
            } finally {
                database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
                try {
                    lockService.releaseLock();
                } catch (LockException e) {
                    LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
                }
                resetServices();
                setChangeExecListener(null);
            }
        }
    });
}
Also used : LockService(liquibase.lockservice.LockService) DatabaseConnection(liquibase.database.DatabaseConnection) Connection(liquibase.hub.model.Connection) Operation(liquibase.hub.model.Operation) InvalidExampleException(liquibase.snapshot.InvalidExampleException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BufferedLogService(liquibase.logging.core.BufferedLogService) CompositeLogService(liquibase.logging.core.CompositeLogService) CommandScope(liquibase.command.CommandScope) HubChangeExecListener(liquibase.hub.listener.HubChangeExecListener) InputStreamList(liquibase.resource.InputStreamList)

Example 8 with Connection

use of liquibase.hub.model.Connection in project liquibase by liquibase.

the class Liquibase method changeLogSync.

/**
 * Changelogsync or changelogsync to tag
 *
 * @param tag
 * @param contexts
 * @param labelExpression
 * @throws LiquibaseException
 */
public void changeLogSync(String tag, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    runInScope(new Scope.ScopedRunner() {

        @Override
        public void run() throws Exception {
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.waitForLock();
            Operation changeLogSyncOperation = null;
            BufferedLogService bufferLog = new BufferedLogService();
            DatabaseChangeLog changeLog = null;
            HubUpdater hubUpdater = null;
            try {
                changeLog = getDatabaseChangeLog();
                checkLiquibaseTables(true, changeLog, contexts, labelExpression);
                ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
                changeLog.validate(database, contexts, labelExpression);
                // 
                // Let the user know that they can register for Hub
                // 
                hubUpdater = new HubUpdater(new Date(), changeLog, database);
                hubUpdater.register(changeLogFile);
                // 
                // Create an iterator which will be used with a ListVisitor
                // to grab the list of change sets for the update
                // 
                ChangeLogIterator listLogIterator = buildChangeLogIterator(tag, changeLog, contexts, labelExpression);
                // 
                // Create or retrieve the Connection
                // Make sure the Hub is available here by checking the return
                // 
                Connection connection = getConnection(changeLog);
                if (connection != null) {
                    String operationCommand = (tag == null ? "changelog-sync" : "changelog-sync-to-tag");
                    changeLogSyncOperation = hubUpdater.preUpdateHub("CHANGELOGSYNC", operationCommand, connection, changeLogFile, contexts, labelExpression, listLogIterator);
                }
                // 
                if (connection != null) {
                    changeLogSyncListener = new HubChangeExecListener(changeLogSyncOperation, changeExecListener);
                }
                ChangeLogIterator runChangeLogIterator = buildChangeLogIterator(tag, changeLog, contexts, labelExpression);
                CompositeLogService compositeLogService = new CompositeLogService(true, bufferLog);
                Scope.child(Scope.Attr.logService.name(), compositeLogService, () -> {
                    runChangeLogIterator.run(new ChangeLogSyncVisitor(database, changeLogSyncListener), new RuntimeEnvironment(database, contexts, labelExpression));
                });
                hubUpdater.postUpdateHub(changeLogSyncOperation, bufferLog);
            } catch (Exception e) {
                if (changeLogSyncOperation != null) {
                    hubUpdater.postUpdateHubExceptionHandling(changeLogSyncOperation, bufferLog, e.getMessage());
                }
                throw e;
            } finally {
                try {
                    lockService.releaseLock();
                } catch (LockException e) {
                    LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
                }
                resetServices();
                setChangeExecListener(null);
            }
        }
    });
}
Also used : LockService(liquibase.lockservice.LockService) DatabaseConnection(liquibase.database.DatabaseConnection) Connection(liquibase.hub.model.Connection) Operation(liquibase.hub.model.Operation) InvalidExampleException(liquibase.snapshot.InvalidExampleException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BufferedLogService(liquibase.logging.core.BufferedLogService) CompositeLogService(liquibase.logging.core.CompositeLogService) CommandScope(liquibase.command.CommandScope) HubChangeExecListener(liquibase.hub.listener.HubChangeExecListener)

Example 9 with Connection

use of liquibase.hub.model.Connection in project liquibase by liquibase.

the class InternalSyncHubCommandStep method run.

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
    CommandScope commandScope = resultsBuilder.getCommandScope();
    final HubServiceFactory hubServiceFactory = Scope.getCurrentScope().getSingleton(HubServiceFactory.class);
    if (!hubServiceFactory.isOnline()) {
        if (commandScope.getArgumentValue(FAIL_IF_OFFLINE_ARG)) {
            throw new CommandExecutionException("The command syncHub requires access to Liquibase Hub: " + hubServiceFactory.getOfflineReason() + ".  Learn more at https://hub.liquibase.com");
        } else {
            Scope.getCurrentScope().getUI().sendMessage("Sync skipped, offline");
            return;
        }
    }
    // 
    // Check for both connection and project specified
    // unless we have said to favor the connectionID
    // 
    final Boolean favorConnectionId = commandScope.getArgumentValue(CONTINUE_IF_CONNECTION_AND_PROJECT_ID_BOTH_SET_ARG);
    final UUID hubConnectionId = commandScope.getArgumentValue(HUB_CONNECTION_ID_ARG);
    if (!favorConnectionId && hubConnectionId != null && commandScope.getArgumentValue(HUB_PROJECT_ID_ARG) != null) {
        String message = "The syncHub command requires only one valid hubConnectionId or hubProjectId or unique URL. Please remove extra values.";
        Scope.getCurrentScope().getLog(getClass()).severe(message);
        throw new CommandExecutionException(message);
    }
    HubChangeLog hubChangeLog = null;
    final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    Connection connectionToSync;
    if (hubConnectionId == null) {
        Project project = null;
        if (StringUtil.isNotEmpty(commandScope.getArgumentValue(CHANGELOG_FILE_ARG))) {
            final ResourceAccessor resourceAccessor = Scope.getCurrentScope().getResourceAccessor();
            final String changelogFile = commandScope.getArgumentValue(CHANGELOG_FILE_ARG);
            final DatabaseChangeLog databaseChangeLog = ChangeLogParserFactory.getInstance().getParser(changelogFile, resourceAccessor).parse(changelogFile, new ChangeLogParameters(), resourceAccessor);
            final String changeLogId = databaseChangeLog.getChangeLogId();
            if (changeLogId == null) {
                Scope.getCurrentScope().getLog(getClass()).info("Changelog " + changelogFile + " has not been registered with Liquibase Hub. Cannot use it to help determine project.");
            } else {
                hubChangeLog = hubService.getHubChangeLog(UUID.fromString(changeLogId), "*");
                if (hubChangeLog == null) {
                    throw new CommandExecutionException("Changelog " + changelogFile + " has an unrecognized changeLogId.");
                }
                if (hubChangeLog.isDeleted()) {
                    // 
                    // Complain and stop the operation
                    // 
                    String message = "\n" + "The operation did not complete and will not be reported to Hub because the\n" + "" + "registered changelog has been deleted by someone in your organization.\n" + "Learn more at http://hub.liquibase.com";
                    throw new LiquibaseHubException(message);
                }
                project = hubChangeLog.getProject();
            }
        } else if (commandScope.getArgumentValue(HUB_PROJECT_ID_ARG) != null) {
            project = hubService.getProject(commandScope.getArgumentValue(HUB_PROJECT_ID_ARG));
            if (project == null) {
                throw new CommandExecutionException("Project Id '" + commandScope.getArgumentValue(HUB_PROJECT_ID_ARG) + "' does not exist or you do not have access to it");
            }
        } else {
            Scope.getCurrentScope().getLog(getClass()).info("No project, connection, or changeLogFile specified. Searching for jdbcUrl across the entire organization.");
        }
        final String url = commandScope.getArgumentValue(URL_ARG);
        final Connection searchConnection = new Connection().setJdbcUrl(url).setProject(project);
        final List<Connection> connections = hubService.getConnections(searchConnection);
        if (connections.size() == 0) {
            if (project == null) {
                throw new CommandExecutionException("The url " + url + " does not match any defined connections. To auto-create a connection, please specify a 'changeLogFile=<changeLogFileName>' in liquibase.properties or the command line which contains a registered changeLogId.");
            }
            Connection inputConnection = new Connection();
            inputConnection.setJdbcUrl(url);
            inputConnection.setProject(project);
            connectionToSync = hubService.createConnection(inputConnection);
        } else if (connections.size() == 1) {
            connectionToSync = connections.get(0);
        } else {
            throw new CommandExecutionException("The url " + url + " is used by more than one connection. Please specify 'hubConnectionId=<hubConnectionId>' or 'changeLogFile=<changeLogFileName>' in liquibase.properties or the command line.");
        }
    } else {
        final List<Connection> connections = hubService.getConnections(new Connection().setId(hubConnectionId));
        if (connections.size() == 0) {
            throw new CommandExecutionException("Hub connection Id " + hubConnectionId + " was either not found, or you do not have access");
        } else {
            connectionToSync = connections.get(0);
        }
    }
    final Database database = commandScope.getArgumentValue(DATABASE_ARG);
    Scope.child(Scope.Attr.database, database, () -> {
        final ChangeLogHistoryService historyService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database);
        final List<RanChangeSet> ranChangeSets = historyService.getRanChangeSets();
        hubService.setRanChangeSets(connectionToSync, ranChangeSets);
    });
    // 
    if (hubChangeLog != null && hubChangeLog.isInactive()) {
        String message = "\n" + "The command completed and reported to Hub, but the changelog has been deactivated by someone in your organization.\n" + "To synchronize your changelog, checkout the latest from source control or run \"deactivatechangelog\".\n" + "After that, commands run against this changelog will not be reported to Hub until \"registerchangelog\" is run again.\n" + "Learn more at http://hub.liquibase.com";
        Scope.getCurrentScope().getLog(HubUpdater.class).warning(message);
        Scope.getCurrentScope().getUI().sendMessage("WARNING: " + message);
    }
}
Also used : ResourceAccessor(liquibase.resource.ResourceAccessor) Connection(liquibase.hub.model.Connection) HubServiceFactory(liquibase.hub.HubServiceFactory) Project(liquibase.hub.model.Project) LiquibaseHubException(liquibase.hub.LiquibaseHubException) HubUpdater(liquibase.hub.HubUpdater) HubChangeLog(liquibase.hub.model.HubChangeLog) Database(liquibase.database.Database) CommandExecutionException(liquibase.exception.CommandExecutionException) UUID(java.util.UUID) HubService(liquibase.hub.HubService)

Aggregations

Connection (liquibase.hub.model.Connection)9 DatabaseConnection (liquibase.database.DatabaseConnection)8 HubChangeExecListener (liquibase.hub.listener.HubChangeExecListener)7 Operation (liquibase.hub.model.Operation)7 LockService (liquibase.lockservice.LockService)7 BufferedLogService (liquibase.logging.core.BufferedLogService)7 CompositeLogService (liquibase.logging.core.CompositeLogService)7 IOException (java.io.IOException)6 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)6 CommandScope (liquibase.command.CommandScope)6 InvalidExampleException (liquibase.snapshot.InvalidExampleException)6 InputStreamList (liquibase.resource.InputStreamList)4 HubChangeLog (liquibase.hub.model.HubChangeLog)2 UUID (java.util.UUID)1 Database (liquibase.database.Database)1 CommandExecutionException (liquibase.exception.CommandExecutionException)1 Executor (liquibase.executor.Executor)1 ExecutorService (liquibase.executor.ExecutorService)1 LoggingExecutor (liquibase.executor.LoggingExecutor)1 HubService (liquibase.hub.HubService)1