Search in sources :

Example 1 with CommandExecutionException

use of liquibase.exception.CommandExecutionException in project liquibase by liquibase.

the class HubUpdater method syncHub.

public void syncHub(String changeLogFile, Connection hubConnection) throws CommandExecutionException {
    // 
    // We pass in a setting of CONTINUE IF_BOTH_CONNECTION_AND_PROJECT_ID_SET_ARG=true
    // to tell syncHub to not complain when both connectionID and projectID
    // are set.
    // 
    UUID hubConnectionId = (hubConnection != null ? hubConnection.getId() : null);
    UUID hubProjectId = (hubConnection != null && hubConnection.getProject() != null ? hubConnection.getProject().getId() : null);
    final CommandScope syncHub = new CommandScope("internalSyncHub").addArgumentValue(InternalSyncHubCommandStep.CHANGELOG_FILE_ARG, changeLogFile).addArgumentValue(InternalSyncHubCommandStep.URL_ARG, database.getConnection().getURL()).addArgumentValue(InternalSyncHubCommandStep.HUB_CONNECTION_ID_ARG, hubConnectionId).addArgumentValue(InternalSyncHubCommandStep.HUB_PROJECT_ID_ARG, hubProjectId).addArgumentValue(InternalSyncHubCommandStep.CONTINUE_IF_CONNECTION_AND_PROJECT_ID_BOTH_SET_ARG, true).addArgumentValue(InternalSyncHubCommandStep.DATABASE_ARG, database).addArgumentValue(InternalSyncHubCommandStep.FAIL_IF_OFFLINE_ARG, false);
    try {
        syncHub.execute();
    } catch (Exception e) {
        Scope.getCurrentScope().getLog(getClass()).warning("Liquibase Hub sync failed: " + e.getMessage(), e);
    }
}
Also used : UUID(java.util.UUID) CommandScope(liquibase.command.CommandScope) LockException(liquibase.exception.LockException) SQLException(java.sql.SQLException) DatabaseException(liquibase.exception.DatabaseException) IOException(java.io.IOException) CommandExecutionException(liquibase.exception.CommandExecutionException) LiquibaseException(liquibase.exception.LiquibaseException)

Example 2 with CommandExecutionException

use of liquibase.exception.CommandExecutionException in project liquibase by liquibase.

the class HubUpdater method register.

/**
 * Automatically register the current user with Hub
 *
 * @param changeLogFile ChangeLog path for this operation
 * @throws LiquibaseException        Thrown if registration fails
 * @throws CommandExecutionException Thrown if registerChangeLog fails
 */
public HubRegisterResponse register(String changeLogFile) throws LiquibaseException {
    HubRegisterResponse registerResponse = null;
    if (!hubService.isOnline()) {
        return null;
    }
    // 
    if (!Scope.getCurrentScope().getUI().getAllowPrompt()) {
        return null;
    }
    // 2.  We have a changelog and a changeLogId in it already
    if (!StringUtil.isEmpty(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue()) || (changeLog != null && changeLog.getChangeLogId() != null)) {
        return null;
    }
    if (skipAutoRegistration != null && skipAutoRegistration) {
        return null;
    }
    // 
    try {
        LockService lockService = LockServiceFactory.getInstance().getLockService(database);
        lockService.releaseLock();
    } catch (LockException e) {
        Scope.getCurrentScope().getLog(HubUpdater.class).warning(Liquibase.MSG_COULD_NOT_RELEASE_LOCK);
    }
    String promptString = "Do you want to see this operation's report in Liquibase Hub, which improves team collaboration? \n" + "If so, enter your email. If not, enter [N] to no longer be prompted, or [S] to skip for now, but ask again next time";
    String input = Scope.getCurrentScope().getUI().prompt(promptString, "S", (input1, returnType) -> {
        input1 = input1.trim().toLowerCase();
        if (!(input1.equals("s") || input1.equals("n") || input1.contains("@"))) {
            throw new IllegalArgumentException(String.format("Invalid value: '%s'", input1));
        }
        return input1;
    }, String.class);
    // 
    // Re-lock before proceeding
    // 
    LockService lockService = LockServiceFactory.getInstance().getLockService(database);
    lockService.waitForLock();
    String defaultsFilePath = Scope.getCurrentScope().get("defaultsFile", String.class);
    File defaultsFile = null;
    if (defaultsFilePath != null) {
        defaultsFile = new File(defaultsFilePath);
    }
    input = input.toLowerCase();
    if (input.equals("n")) {
        // 
        try {
            String message = "No operations will be reported. Simply add a liquibase.hub.apiKey setting to generate free deployment reports. Learn more at https://hub.liquibase.com";
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(getClass()).info(message);
            writeToPropertiesFile(defaultsFile, "\nliquibase.hub.mode=off\n");
            message = "* Updated properties file " + defaultsFile + " to set liquibase.hub.mode=off";
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(getClass()).info(message);
            DeprecatedConfigurationValueProvider.setData(HubConfiguration.LIQUIBASE_HUB_MODE, HubConfiguration.HubMode.OFF);
        } catch (IOException ioe) {
            String message = "Unable to write hubMode to liquibase.properties: " + ioe.getMessage();
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(getClass()).warning(message);
        }
    } else if (input.equals("s")) {
        String message = "Skipping auto-registration";
        Scope.getCurrentScope().getUI().sendMessage(message);
        Scope.getCurrentScope().getLog(getClass()).warning(message);
        skipAutoRegistration = true;
    } else {
        // 
        try {
            registerResponse = hubService.register(input);
        } catch (LiquibaseException lhe) {
            String message = "Account creation failed for email address '" + input + "': " + lhe.getMessage() + ".\n" + "No operation report will be generated.";
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(HubUpdater.class).warning(message);
            return registerResponse;
        }
        if (registerResponse == null) {
            String message = "Account creation failed for email address '" + input + "'.\n" + "No operation report will be generated.";
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(HubUpdater.class).warning(message);
            return registerResponse;
        }
        String message;
        try {
            // 
            // Update the properties file
            // 
            writeToPropertiesFile(defaultsFile, "\nliquibase.hub.apiKey=" + registerResponse.getApiKey() + "\n");
            // 
            // If there is no liquibase.hub.mode setting then add one with value 'all'
            // Do not update liquibase.hub.mode if it is already set
            // 
            ConfiguredValue<HubConfiguration.HubMode> hubModeProperty = HubConfiguration.LIQUIBASE_HUB_MODE.getCurrentConfiguredValue();
            if (hubModeProperty.wasDefaultValueUsed()) {
                writeToPropertiesFile(defaultsFile, "\nliquibase.hub.mode=all\n");
                message = "* Updated properties file " + defaultsFile + " to set liquibase.hub properties";
                Scope.getCurrentScope().getUI().sendMessage(message);
                Scope.getCurrentScope().getLog(getClass()).info(message);
            } else {
                message = "* Updated the liquibase.hub.apiKey property.";
                String message2 = "The liquibase.hub.mode is already set to " + hubModeProperty.getValue() + ". It will not be updated.";
                Scope.getCurrentScope().getUI().sendMessage(message);
                Scope.getCurrentScope().getUI().sendMessage(message2);
                Scope.getCurrentScope().getLog(getClass()).warning(message);
                Scope.getCurrentScope().getLog(getClass()).warning(message2);
            }
            // register the changelog if it exist
            DeprecatedConfigurationValueProvider.setData(HubConfiguration.LIQUIBASE_HUB_API_KEY, registerResponse.getApiKey());
            if (changeLog != null) {
                message = "* Registering changelog file " + changeLogFile + " with Hub";
                Scope.getCurrentScope().getUI().sendMessage(message);
                Scope.getCurrentScope().getLog(getClass()).info(message);
                // Update the API key in HubConfiguration
                registerChangeLog(registerResponse.getProjectId(), changeLog, changeLogFile);
            }
            message = "Great! Your free operation and deployment reports will be available to you after your local Liquibase commands complete.";
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(getClass()).info(message);
        } catch (IOException ioe) {
            message = "Unable to write information to liquibase.properties: " + ioe.getMessage() + "\n" + "Please check your permissions.  No operations will be reported.";
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(getClass()).warning(message);
        } catch (CommandExecutionException cee) {
            message = "Unable to register changelog: " + cee.getMessage() + "\n" + "No operations will be reported.";
            Scope.getCurrentScope().getUI().sendMessage(message);
            Scope.getCurrentScope().getLog(getClass()).warning(message);
            // System.setProperty(HubConfiguration.LIQUIBASE_HUB_API_KEY.getKey(), null);
            DeprecatedConfigurationValueProvider.setData(HubConfiguration.LIQUIBASE_HUB_API_KEY, null);
        }
    }
    return registerResponse;
}
Also used : LockService(liquibase.lockservice.LockService) LockException(liquibase.exception.LockException) ConfiguredValue(liquibase.configuration.ConfiguredValue) CommandExecutionException(liquibase.exception.CommandExecutionException) IOException(java.io.IOException) LiquibaseException(liquibase.exception.LiquibaseException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 3 with CommandExecutionException

use of liquibase.exception.CommandExecutionException in project liquibase by liquibase.

the class CommandLineUtils method doDiff.

public static void doDiff(Database referenceDatabase, Database targetDatabase, String snapshotTypes, CompareControl.SchemaComparison[] schemaComparisons, ObjectChangeFilter objectChangeFilter, PrintStream output) throws LiquibaseException {
    CommandScope diffCommand = createDiffCommand(referenceDatabase, targetDatabase, snapshotTypes, schemaComparisons, objectChangeFilter, output);
    Scope.getCurrentScope().getUI().sendMessage("");
    Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("diff.results"));
    try {
        diffCommand.execute();
    } catch (CommandExecutionException e) {
        throw new LiquibaseException(e);
    }
}
Also used : CommandExecutionException(liquibase.exception.CommandExecutionException) LiquibaseException(liquibase.exception.LiquibaseException) CommandScope(liquibase.command.CommandScope)

Example 4 with CommandExecutionException

use of liquibase.exception.CommandExecutionException 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 5 with CommandExecutionException

use of liquibase.exception.CommandExecutionException 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)

Aggregations

CommandExecutionException (liquibase.exception.CommandExecutionException)13 LiquibaseException (liquibase.exception.LiquibaseException)5 CommandScope (liquibase.command.CommandScope)4 HubServiceFactory (liquibase.hub.HubServiceFactory)4 UUID (java.util.UUID)3 HubService (liquibase.hub.HubService)3 HubChangeLog (liquibase.hub.model.HubChangeLog)3 Project (liquibase.hub.model.Project)3 IOException (java.io.IOException)2 PrintWriter (java.io.PrintWriter)2 ChangelogRewriter (liquibase.changelog.ChangelogRewriter)2 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)2 CompareControl (liquibase.diff.compare.CompareControl)2 LockException (liquibase.exception.LockException)2 File (java.io.File)1 OutputStream (java.io.OutputStream)1 PrintStream (java.io.PrintStream)1 RandomAccessFile (java.io.RandomAccessFile)1 SQLException (java.sql.SQLException)1 CatalogAndSchema (liquibase.CatalogAndSchema)1