Search in sources :

Example 1 with HubChangeLog

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

the class HubChangeExecListener method updateHubForRollback.

// 
// Send an update message to Hub for this change set rollback
// 
private void updateHubForRollback(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, String operationStatusType, String statusMessage) {
    if (operation == null) {
        String apiKey = StringUtil.trimToNull(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue());
        boolean hubOn = HubConfiguration.LIQUIBASE_HUB_MODE.getCurrentValue() != HubConfiguration.HubMode.OFF;
        if (apiKey != null && hubOn) {
            String message = "Hub communication failure.\n" + "The data for operation on changeset '" + changeSet.getId() + "' by author '" + changeSet.getAuthor() + "'\n" + "was not successfully recorded in your Liquibase Hub project";
            Scope.getCurrentScope().getUI().sendMessage(message);
            logger.info(message);
        }
        return;
    }
    HubChangeLog hubChangeLog;
    final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    try {
        hubChangeLog = hubService.getHubChangeLog(UUID.fromString(databaseChangeLog.getChangeLogId()));
        if (hubChangeLog == null) {
            logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
            return;
        }
    } catch (LiquibaseHubException lhe) {
        logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
        return;
    }
    Date dateExecuted = new Date();
    // 
    // POST /organizations/{id}/projects/{id}/operations/{id}/change-events
    // 
    OperationChangeEvent operationChangeEvent = new OperationChangeEvent();
    operationChangeEvent.setEventType("ROLLBACK");
    operationChangeEvent.setStartDate(startDateMap.get(changeSet));
    operationChangeEvent.setEndDate(dateExecuted);
    operationChangeEvent.setDateExecuted(dateExecuted);
    operationChangeEvent.setChangesetId(changeSet.getId());
    operationChangeEvent.setChangesetFilename(changeSet.getFilePath());
    operationChangeEvent.setChangesetAuthor(changeSet.getAuthor());
    List<String> sqlList = new ArrayList<>();
    try {
        if (rollbackScriptContents != null) {
            sqlList.add(rollbackScriptContents);
        } else if (changeSet.hasCustomRollbackChanges()) {
            List<Change> changes = changeSet.getRollback().getChanges();
            for (Change change : changes) {
                SqlStatement[] statements = change.generateStatements(database);
                for (SqlStatement statement : statements) {
                    for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, database)) {
                        sqlList.add(sql.toSql());
                    }
                }
            }
        } else {
            List<Change> changes = changeSet.getChanges();
            for (Change change : changes) {
                SqlStatement[] statements = change.generateRollbackStatements(database);
                for (SqlStatement statement : statements) {
                    for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, database)) {
                        sqlList.add(sql.toSql());
                    }
                }
            }
        }
    } catch (LiquibaseException lbe) {
        logger.warning(lbe.getMessage());
    }
    String[] sqlArray = new String[sqlList.size()];
    sqlArray = sqlList.toArray(sqlArray);
    operationChangeEvent.setGeneratedSql(sqlArray);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ChangeLogSerializer serializer = ChangeLogSerializerFactory.getInstance().getSerializer(".json");
    try {
        serializer.write(Collections.singletonList(changeSet), baos);
        operationChangeEvent.setChangesetBody(baos.toString("UTF-8"));
    } catch (IOException ioe) {
    // 
    // Consume
    // 
    }
    operationChangeEvent.setOperationStatusType(operationStatusType);
    operationChangeEvent.setStatusMessage(statusMessage);
    if ("FAIL".equals(operationStatusType)) {
        operationChangeEvent.setLogs(statusMessage);
    } else {
        String logs = getCurrentLog();
        if (!StringUtil.isEmpty(logs)) {
            operationChangeEvent.setLogs(logs);
        } else {
            operationChangeEvent.setLogs(statusMessage);
        }
    }
    operationChangeEvent.setLogsTimestamp(new Date());
    operationChangeEvent.setProject(hubChangeLog.getProject());
    operationChangeEvent.setOperation(operation);
    try {
        hubService.sendOperationChangeEvent(operationChangeEvent);
        postCount++;
    } catch (LiquibaseException lbe) {
        logger.warning(lbe.getMessage(), lbe);
        logger.warning("Unable to send Operation Change Event for operation '" + operation.getId().toString() + " change set '" + changeSet.toString(false));
    }
}
Also used : HubServiceFactory(liquibase.hub.HubServiceFactory) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) Change(liquibase.change.Change) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Sql(liquibase.sql.Sql) SqlStatement(liquibase.statement.SqlStatement) LiquibaseHubException(liquibase.hub.LiquibaseHubException) HubChangeLog(liquibase.hub.model.HubChangeLog) OperationChangeEvent(liquibase.hub.model.OperationChangeEvent) LiquibaseException(liquibase.exception.LiquibaseException) HubService(liquibase.hub.HubService)

Example 2 with HubChangeLog

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

the class HubChangeExecListener method updateHub.

// 
// Send an update message to Hub for this change set
// 
private void updateHub(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, String eventType, String operationStatusType, String statusMessage) {
    // 
    if (operation == null) {
        String apiKey = StringUtil.trimToNull(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValueObfuscated());
        boolean hubOn = HubConfiguration.LIQUIBASE_HUB_MODE.getCurrentValue() != HubConfiguration.HubMode.OFF;
        if (apiKey != null && hubOn) {
            String message;
            if (databaseChangeLog.getChangeLogId() == null) {
                message = "The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Liquibase Hub.\n" + "To register the changelog with your Hub Project run 'liquibase registerChangeLog'.\n" + "Learn more at https://hub.liquibase.com.";
            } else {
                message = "The changelog file specified is not registered with any Liquibase Hub project, so the results will not be recorded in Liquibase Hub.\n" + "To register the changelog with your Hub Project run 'liquibase registerChangeLog'.\n" + "Learn more at https://hub.liquibase.com.";
            }
            Scope.getCurrentScope().getUI().sendMessage(message);
            logger.info(message);
        }
        return;
    }
    HubChangeLog hubChangeLog;
    final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    try {
        hubChangeLog = hubService.getHubChangeLog(UUID.fromString(databaseChangeLog.getChangeLogId()));
        if (hubChangeLog == null) {
            logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
            return;
        }
    } catch (LiquibaseHubException lhe) {
        logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
        return;
    }
    // 
    // POST /organizations/{id}/projects/{id}/operations/{id}/change-events
    // Do not send generated SQL or changeset body for changeLogSync operation
    // 
    OperationChangeEvent operationChangeEvent = new OperationChangeEvent();
    List<String> sqlList = new ArrayList<>();
    if (!eventType.equals("SYNC")) {
        List<Change> changes = changeSet.getChanges();
        for (Change change : changes) {
            try {
                Sql[] sqls = SqlGeneratorFactory.getInstance().generateSql(change, database);
                for (Sql sql : sqls) {
                    sqlList.add(sql.toSql());
                }
            } catch (Exception e) {
                logger.warning("Unable to generate SQL for Hub failure message: " + e.getMessage());
            }
        }
        String[] sqlArray = new String[sqlList.size()];
        sqlArray = sqlList.toArray(sqlArray);
        operationChangeEvent.setGeneratedSql(sqlArray);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ChangeLogSerializer serializer = ChangeLogSerializerFactory.getInstance().getSerializer(".json");
        try {
            serializer.write(Collections.singletonList(changeSet), baos);
            operationChangeEvent.setChangesetBody(baos.toString("UTF-8"));
        } catch (IOException ioe) {
            // 
            // Just log message
            // 
            logger.warning("Unable to serialize change set '" + changeSet.toString(false) + "' for Hub.");
        }
    }
    Date dateExecuted = new Date();
    String[] sqlArray = new String[sqlList.size()];
    sqlArray = sqlList.toArray(sqlArray);
    operationChangeEvent.setEventType(eventType);
    operationChangeEvent.setStartDate(startDateMap.get(changeSet));
    operationChangeEvent.setEndDate(dateExecuted);
    operationChangeEvent.setDateExecuted(dateExecuted);
    operationChangeEvent.setChangesetId(changeSet.getId());
    operationChangeEvent.setChangesetFilename(changeSet.getFilePath());
    operationChangeEvent.setChangesetAuthor(changeSet.getAuthor());
    operationChangeEvent.setOperationStatusType(operationStatusType);
    operationChangeEvent.setStatusMessage(statusMessage);
    operationChangeEvent.setGeneratedSql(sqlArray);
    operationChangeEvent.setOperation(operation);
    operationChangeEvent.setLogsTimestamp(new Date());
    if ("FAIL".equals(operationStatusType)) {
        operationChangeEvent.setLogs(statusMessage);
    } else {
        String logs = getCurrentLog();
        if (!StringUtil.isEmpty(logs)) {
            operationChangeEvent.setLogs(logs);
        } else {
            operationChangeEvent.setLogs(statusMessage);
        }
    }
    operationChangeEvent.setProject(hubChangeLog.getProject());
    operationChangeEvent.setOperation(operation);
    try {
        hubService.sendOperationChangeEvent(operationChangeEvent);
        postCount++;
    } catch (LiquibaseException lbe) {
        logger.warning(lbe.getMessage(), lbe);
        logger.warning("Unable to send Operation Change Event for operation '" + operation.getId().toString() + " change set '" + changeSet.toString(false));
        failedToPostCount++;
    }
}
Also used : HubServiceFactory(liquibase.hub.HubServiceFactory) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) Change(liquibase.change.Change) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) LiquibaseHubException(liquibase.hub.LiquibaseHubException) PreconditionErrorException(liquibase.exception.PreconditionErrorException) IOException(java.io.IOException) PreconditionFailedException(liquibase.exception.PreconditionFailedException) LiquibaseException(liquibase.exception.LiquibaseException) Sql(liquibase.sql.Sql) LiquibaseHubException(liquibase.hub.LiquibaseHubException) HubChangeLog(liquibase.hub.model.HubChangeLog) OperationChangeEvent(liquibase.hub.model.OperationChangeEvent) LiquibaseException(liquibase.exception.LiquibaseException) HubService(liquibase.hub.HubService)

Example 3 with HubChangeLog

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

the class DeactivateChangelogCommandStep method run.

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
    CommandScope commandScope = resultsBuilder.getCommandScope();
    try (PrintWriter output = new PrintWriter(resultsBuilder.getOutputStream())) {
        // 
        // Access the HubService
        // Stop if we do no have a key
        // 
        final HubServiceFactory hubServiceFactory = Scope.getCurrentScope().getSingleton(HubServiceFactory.class);
        if (!hubServiceFactory.isOnline()) {
            throw new CommandExecutionException("The command deactivateChangeLog requires communication with Liquibase Hub, \nwhich is prevented by liquibase.hub.mode='off'. \nPlease set to 'all' or 'meta' and try again. \nLearn more at https://hub.liquibase.com");
        }
        // 
        // Check for existing changeLog file
        // 
        String changeLogFile = commandScope.getArgumentValue(CHANGELOG_FILE_ARG);
        DatabaseChangeLog databaseChangeLog = parseChangeLogFile(changeLogFile);
        final String changeLogId = (databaseChangeLog != null ? databaseChangeLog.getChangeLogId() : null);
        if (changeLogId == null) {
            throw new CommandExecutionException("Changelog '" + changeLogFile + "' does not have a changelog ID and is not registered with Hub.\n" + "For more information visit https://docs.liquibase.com.");
        }
        final HubService service = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
        HubChangeLog hubChangeLog = service.getHubChangeLog(UUID.fromString(changeLogId));
        if (hubChangeLog == null) {
            String message = "WARNING: Changelog '" + changeLogFile + "' has a changelog ID but was not found in Hub.\n" + "The changelog ID will be removed from the file, but Hub will not be updated.";
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(DeactivateChangelogCommandStep.class).warning(message);
        } else {
            // 
            // Update Hub to deactivate the changelog
            // 
            hubChangeLog.setStatus("INACTIVE");
            hubChangeLog = service.deactivateChangeLog(hubChangeLog);
        }
        // 
        // Remove the changeLog Id and update the file
        // 
        ChangelogRewriter.ChangeLogRewriterResult rewriterResult = ChangelogRewriter.removeChangeLogId(changeLogFile, changeLogId, databaseChangeLog);
        String message = null;
        if (rewriterResult.success) {
            message = "The changelog '" + changeLogFile + "' was deactivated.\n" + "Note: If this is a shared changelog, please check it into Source Control.\n" + "Operation data sent to the now inactive changelogID will still be accepted at Hub.\n" + "For more information visit https://docs.liquibase.com.\n";
            Scope.getCurrentScope().getLog(DeactivateChangelogCommandStep.class).info(message);
            output.println(message);
            resultsBuilder.addResult("statusCode", 0);
            return;
        }
        throw new CommandExecutionException(rewriterResult.message);
    }
}
Also used : ChangelogRewriter(liquibase.changelog.ChangelogRewriter) HubChangeLog(liquibase.hub.model.HubChangeLog) HubServiceFactory(liquibase.hub.HubServiceFactory) CommandExecutionException(liquibase.exception.CommandExecutionException) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) HubService(liquibase.hub.HubService) PrintWriter(java.io.PrintWriter)

Example 4 with HubChangeLog

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

the class RegisterChangelogCommandStep method doRegisterChangelog.

public void doRegisterChangelog(String changelogFilepath, UUID hubProjectId, String hubProjectName, CommandResultsBuilder resultsBuilder, boolean skipPromptIfOneProject) throws LiquibaseException, CommandLineParsingException {
    try (PrintWriter output = new PrintWriter(resultsBuilder.getOutputStream())) {
        HubChangeLog hubChangeLog;
        final HubService service = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
        // 
        // Check for existing changeLog file using the untouched changelog filepath
        // 
        DatabaseChangeLog databaseChangeLog = parseChangeLogFile(changelogFilepath);
        if (databaseChangeLog == null) {
            throw new CommandExecutionException("Cannot parse " + changelogFilepath);
        }
        final String changeLogId = databaseChangeLog.getChangeLogId();
        if (changeLogId != null) {
            hubChangeLog = service.getHubChangeLog(UUID.fromString(changeLogId));
            if (hubChangeLog != null) {
                throw new CommandExecutionException("Changelog '" + changelogFilepath + "' is already registered with changeLogId '" + changeLogId + "' to project '" + hubChangeLog.getProject().getName() + "' with project ID '" + hubChangeLog.getProject().getId().toString() + "'.\n" + "For more information visit https://docs.liquibase.com.", new ChangeLogAlreadyRegisteredException(hubChangeLog));
            } else {
                throw new CommandExecutionException("Changelog '" + changelogFilepath + "' is already registered with changeLogId '" + changeLogId + "'.\n" + "For more information visit https://docs.liquibase.com.", new ChangeLogAlreadyRegisteredException());
            }
        }
        // 
        // Retrieve the projects
        // 
        Project project;
        if (hubProjectId != null) {
            project = service.getProject(hubProjectId);
            if (project == null) {
                throw new CommandExecutionException("Project Id '" + hubProjectId + "' does not exist or you do not have access to it");
            }
        } else if (hubProjectName != null) {
            if (hubProjectName.length() > 255) {
                throw new CommandExecutionException("\nThe project name you gave is longer than 255 characters\n\n");
            }
            project = service.createProject(new Project().setName(hubProjectName));
            if (project == null) {
                throw new CommandExecutionException("Unable to create project '" + hubProjectName + "'.\n" + "Learn more at https://hub.liquibase.com.");
            }
            output.print("\nProject '" + project.getName() + "' created with project ID '" + project.getId() + "'.\n\n");
        } else {
            project = retrieveOrCreateProject(service, changelogFilepath, skipPromptIfOneProject);
            if (project == null) {
                throw new CommandExecutionException("Your changelog " + changelogFilepath + " was not registered to any Liquibase Hub project. You can still run Liquibase commands, but no data will be saved in your Liquibase Hub account for monitoring or reports.  Learn more at https://hub.liquibase.com.");
            }
        }
        // 
        // Go create the Hub Changelog
        // 
        String changelogFilename = Paths.get(databaseChangeLog.getFilePath()).getFileName().toString();
        HubChangeLog newChangeLog = new HubChangeLog();
        newChangeLog.setProject(project);
        newChangeLog.setFileName(changelogFilename);
        newChangeLog.setName(changelogFilename);
        hubChangeLog = service.createChangeLog(newChangeLog);
        // 
        // Update the changelog file
        // Add the registered changelog ID to the results so that
        // the caller can use it
        // 
        ChangelogRewriter.ChangeLogRewriterResult changeLogRewriterResult = ChangelogRewriter.addChangeLogId(changelogFilepath, hubChangeLog.getId().toString(), databaseChangeLog);
        if (changeLogRewriterResult.success) {
            Scope.getCurrentScope().getLog(RegisterChangelogCommandStep.class).info(changeLogRewriterResult.message);
            output.println("* Changelog file '" + changelogFilepath + "' with changelog ID '" + hubChangeLog.getId().toString() + "' has been " + "registered to Project " + project.getName());
            resultsBuilder.addResult("statusCode", 0);
            resultsBuilder.addResult(REGISTERED_CHANGELOG_ID.getName(), hubChangeLog.getId().toString());
        }
    }
}
Also used : Project(liquibase.hub.model.Project) ChangelogRewriter(liquibase.changelog.ChangelogRewriter) ChangeLogAlreadyRegisteredException(liquibase.exception.ChangeLogAlreadyRegisteredException) HubChangeLog(liquibase.hub.model.HubChangeLog) HubServiceFactory(liquibase.hub.HubServiceFactory) CommandExecutionException(liquibase.exception.CommandExecutionException) HubService(liquibase.hub.HubService) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) PrintWriter(java.io.PrintWriter)

Example 5 with HubChangeLog

use of liquibase.hub.model.HubChangeLog 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)

Aggregations

HubChangeLog (liquibase.hub.model.HubChangeLog)7 HubService (liquibase.hub.HubService)6 HubServiceFactory (liquibase.hub.HubServiceFactory)6 LiquibaseHubException (liquibase.hub.LiquibaseHubException)4 CommandExecutionException (liquibase.exception.CommandExecutionException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 PrintWriter (java.io.PrintWriter)2 Change (liquibase.change.Change)2 ChangelogRewriter (liquibase.changelog.ChangelogRewriter)2 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)2 LiquibaseException (liquibase.exception.LiquibaseException)2 Connection (liquibase.hub.model.Connection)2 OperationChangeEvent (liquibase.hub.model.OperationChangeEvent)2 Project (liquibase.hub.model.Project)2 ChangeLogSerializer (liquibase.serializer.ChangeLogSerializer)2 Sql (liquibase.sql.Sql)2 UUID (java.util.UUID)1 Database (liquibase.database.Database)1 DatabaseConnection (liquibase.database.DatabaseConnection)1