use of liquibase.hub.HubService 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));
}
}
use of liquibase.hub.HubService 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++;
}
}
use of liquibase.hub.HubService 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);
}
}
use of liquibase.hub.HubService in project liquibase by liquibase.
the class RegisterChangelogCommandStep method getProjectsFromHub.
//
// Retrieve the projects and sort them by create date
//
private List<Project> getProjectsFromHub() throws LiquibaseHubException {
final HubService service = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
List<Project> projects = service.getProjects();
Collections.sort(projects, new Comparator<Project>() {
@Override
public int compare(Project o1, Project o2) {
Date date1 = o1.getCreateDate();
Date date2 = o2.getCreateDate();
return date2.compareTo(date1);
}
});
return projects;
}
use of liquibase.hub.HubService 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());
}
}
}
Aggregations