use of org.jvnet.hk2.config.Changed.TYPE in project Payara by payara.
the class InstanceDeployCommand method execute.
@Override
public void execute(AdminCommandContext ctxt) {
long operationStartTime = Calendar.getInstance().getTimeInMillis();
final ActionReport report = ctxt.getActionReport();
final Logger logger = ctxt.getLogger();
ReadableArchive archive = null;
this.origin = Origin.deploy_instance;
this.command = Command._deploy;
this.previousContextRoot = preservedcontextroot;
if (previousVirtualServers != null) {
String vs = previousVirtualServers.getProperty(target);
if (vs != null) {
this.virtualservers = vs;
}
}
if (previousEnabledAttributes != null) {
String enabledAttr = previousEnabledAttributes.getProperty(target);
if (enabledAttr != null) {
String enabledAttrForApp = previousEnabledAttributes.getProperty(DeploymentUtils.DOMAIN_TARGET_NAME);
this.enabled = Boolean.valueOf(enabledAttr) && Boolean.valueOf(enabledAttrForApp);
}
}
try {
if (!path.exists()) {
report.setMessage(localStrings.getLocalString("fnf", "File not found", path.getAbsolutePath()));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return;
}
if (snifferManager.hasNoSniffers()) {
String msg = localStrings.getLocalString("nocontainer", "No container services registered, done...");
report.failure(logger, msg);
return;
}
archive = archiveFactory.openArchive(path, this);
ArchiveHandler archiveHandler = deployment.getArchiveHandler(archive, type);
if (archiveHandler == null) {
report.failure(logger, localStrings.getLocalString("deploy.unknownarchivetype", "Archive type of {0} was not recognized", path.getName()));
return;
}
// wait until all applications are loaded as we may have dependency on these, or the previous app is still
// starting
startupProvider.get();
// clean up any left over repository files
if (!keepreposdir.booleanValue()) {
FileUtils.whack(new File(env.getApplicationRepositoryPath(), VersioningUtils.getRepositoryName(name)));
}
ExtendedDeploymentContext deploymentContext = deployment.getBuilder(logger, this, report).source(archive).build();
// clean up any remaining generated files
deploymentContext.clean();
deploymentContext.getAppProps().putAll(appprops);
processGeneratedContent(generatedcontent, deploymentContext, logger);
Transaction t = null;
Application application = applications.getApplication(name);
if (application != null) {
// application element already been synchronized over
t = new Transaction();
} else {
t = deployment.prepareAppConfigChanges(deploymentContext);
}
ApplicationInfo appInfo;
appInfo = deployment.deploy(deploymentContext);
if (report.getActionExitCode() == ActionReport.ExitCode.SUCCESS) {
try {
moveAltDDFilesToPermanentLocation(deploymentContext, logger);
// register application information in domain.xml
if (application != null) {
// application element already synchronized over
// just write application-ref
deployment.registerAppInDomainXML(appInfo, deploymentContext, t, true);
} else {
// write both application and application-ref
deployment.registerAppInDomainXML(appInfo, deploymentContext, t);
}
} catch (Exception e) {
// roll back the deployment and re-throw the exception
deployment.undeploy(name, deploymentContext);
deploymentContext.clean();
throw e;
}
}
} catch (Throwable e) {
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
report.setMessage(e.getMessage());
report.setFailureCause(e);
} finally {
try {
if (archive != null) {
archive.close();
}
} catch (IOException e) {
logger.log(Level.INFO, localStrings.getLocalString("errClosingArtifact", "Error while closing deployable artifact : ", path.getAbsolutePath()), e);
}
if (report.getActionExitCode().equals(ActionReport.ExitCode.SUCCESS)) {
logger.info(localStrings.getLocalString("deploy.done", "Deployment of {0} done is {1} ms", name, (Calendar.getInstance().getTimeInMillis() - operationStartTime)));
} else if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
String errorMessage = report.getMessage();
Throwable cause = report.getFailureCause();
if (cause != null) {
String causeMessage = cause.getMessage();
if (causeMessage != null && !causeMessage.equals(errorMessage)) {
errorMessage = errorMessage + " : " + cause.getMessage();
}
logger.log(Level.SEVERE, errorMessage, cause.getCause());
}
report.setMessage(localStrings.getLocalString("failToLoadOnInstance", "Failed to load the application on instance {0} : {1}", server.getName(), errorMessage));
// reset the failure cause so command framework will not try
// to print the same message again
report.setFailureCause(null);
}
}
}
use of org.jvnet.hk2.config.Changed.TYPE in project Payara by payara.
the class DeployCommand method execute.
/**
* Entry point from the framework into the command execution
*
* @param context context for the command.
*/
@Override
public void execute(AdminCommandContext context) {
long timeTakenToDeploy = 0;
long deploymentTimeMillis = 0;
Optional<ApplicationState> appState = Optional.empty();
final ActionReport report = context.getActionReport();
try (SpanSequence span = structuredTracing.startSequence(DeploymentTracing.AppStage.VALIDATE_TARGET, "registry")) {
if (!hotDeploy) {
hotDeployService.removeApplicationState(initialContext.getSourceDir());
} else if (!(appState = hotDeployService.getApplicationState(initialContext.getSourceDir())).isPresent()) {
ApplicationState applicationState = new ApplicationState(name, path, initialContext);
applicationState.setTarget(target);
appState = Optional.of(applicationState);
}
// needs to be fixed in hk2, we don't generate the right innerclass index. it should use $
Collection<Interceptor> interceptors = habitat.getAllServices(Interceptor.class);
if (interceptors != null) {
for (Interceptor interceptor : interceptors) {
interceptor.intercept(this, initialContext);
}
}
deployment.validateDeploymentTarget(target, name, isredeploy);
ActionReport.MessagePart part = report.getTopMessagePart();
part.addProperty(DeploymentProperties.NAME, name);
ApplicationConfigInfo savedAppConfig = new ApplicationConfigInfo(apps.getModule(Application.class, name));
Properties undeployProps = null;
if (appState.map(ApplicationState::isInactive).orElse(true)) {
undeployProps = handleRedeploy(name, report, context);
}
appState.filter(ApplicationState::isInactive).ifPresent(hotDeployService::addApplicationState);
if (enabled == null) {
enabled = Boolean.TRUE;
}
// clean up any left over repository files
if (!keepreposdir) {
span.start(DeploymentTracing.AppStage.CLEANUP, "applications");
final File reposDir = new File(env.getApplicationRepositoryPath(), VersioningUtils.getRepositoryName(name));
if (reposDir.exists()) {
for (int i = 0; i < domain.getApplications().getApplications().size(); i++) {
File existrepos = new File(new URI(domain.getApplications().getApplications().get(i).getLocation()));
String appname = domain.getApplications().getApplications().get(i).getName();
if (!appname.equals(name) && existrepos.getAbsoluteFile().equals(reposDir.getAbsoluteFile())) {
report.failure(logger, localStrings.getLocalString("deploy.dupdeployment", "Application {0} is trying to use the same repository directory as application {1}, please choose a different application name to deploy", name, appname));
return;
}
}
/*
* Delete the repository directory as an archive to allow
* any special processing (such as stale file handling)
* to run.
*/
final FileArchive arch = DeploymentUtils.openAsFileArchive(reposDir, archiveFactory);
arch.delete();
}
span.finish();
}
if (!DeploymentUtils.isDomainTarget(target) && enabled) {
// try to disable the enabled version, if exist
try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.SWITCH_VERSIONS)) {
versioningService.handleDisable(name, target, report, context.getSubject());
} catch (VersioningSyntaxException e) {
report.failure(logger, e.getMessage());
return;
}
}
File source = new File(archive.getURI().getSchemeSpecificPart());
boolean isDirectoryDeployed = true;
if (!source.isDirectory()) {
isDirectoryDeployed = false;
expansionDir = new File(domain.getApplicationRoot(), VersioningUtils.getRepositoryName(name));
path = expansionDir;
} else {
// test if a version is already directory deployed from this dir
String versionFromSameDir = versioningService.getVersionFromSameDir(source);
if (!force && versionFromSameDir != null) {
report.failure(logger, VersioningUtils.LOCALSTRINGS.getLocalString("versioning.deployment.dual.inplace", "GlassFish do not support versioning for directory deployment when using the same directory. The directory {0} is already assigned to the version {1}.", source.getPath(), versionFromSameDir));
return;
}
}
span.start(DeploymentTracing.AppStage.CREATE_DEPLOYMENT_CONTEXT, "Full");
// create the parent class loader
deploymentContext = deployment.getBuilder(logger, this, report).source(initialContext.getSource()).archiveHandler(archiveHandler).build(initialContext);
String transformNS = System.getProperty(TRANSFORM_NAMESPACE);
Types types = deployment.getDeployableTypes(deploymentContext);
if (Boolean.valueOf(transformNS) || (transformNS == null && PayaraTransformer.isJakartaEEApplication(types))) {
span.start(DeploymentTracing.AppStage.TRANSFORM_ARCHIVE);
deploymentContext.getSource().close();
File output = PayaraTransformer.transformApplication(path, context, isDirectoryDeployed);
if (output == null) {
return;
}
deploymentContext.setSource((FileArchive) archiveFactory.createArchive(output));
// reset transient and module data of orignal deployed archive
deploymentContext.removeTransientAppMetaData(Types.class.getName());
deploymentContext.removeTransientAppMetaData(Parser.class.getName());
deploymentContext.resetModuleMetaData();
structuredTracing.register(deploymentContext);
}
// reset the properties (might be null) set by the deployers when undeploying.
if (undeployProps != null) {
deploymentContext.getAppProps().putAll(undeployProps);
}
if (properties != null || property != null) {
// check for both
if (properties == null) {
properties = new Properties();
}
if (property != null) {
properties.putAll(property);
}
}
if (properties != null) {
deploymentContext.getAppProps().putAll(properties);
validateDeploymentProperties(properties, deploymentContext);
}
span.start(DeploymentTracing.AppStage.CLEANUP, "generated");
// clean up any generated files
deploymentContext.clean();
span.start(DeploymentTracing.AppStage.PREPARE, "ServerConfig");
Properties appProps = deploymentContext.getAppProps();
/*
* If the app's location is within the domain's directory then
* express it in the config as ${com.sun.aas.instanceRootURI}/rest-of-path
* so users can relocate the entire installation without having
* to modify the app locations. Leave the location alone if
* it does not fall within the domain directory.
*/
String appLocation = DeploymentUtils.relativizeWithinDomainIfPossible(deploymentContext.getSource().getURI());
appProps.setProperty(ServerTags.LOCATION, appLocation);
// set to default "user", deployers can override it
// during processing
appProps.setProperty(ServerTags.OBJECT_TYPE, "user");
if (contextroot != null) {
appProps.setProperty(ServerTags.CONTEXT_ROOT, contextroot);
}
appProps.setProperty(ServerTags.DIRECTORY_DEPLOYED, String.valueOf(isDirectoryDeployed));
if (type == null) {
type = archiveHandler.getArchiveType();
}
appProps.setProperty(Application.ARCHIVE_TYPE_PROP_NAME, type);
if (appProps.getProperty(ServerTags.CDI_DEV_MODE_ENABLED_PROP) == null) {
appProps.setProperty(ServerTags.CDI_DEV_MODE_ENABLED_PROP, Boolean.FALSE.toString());
}
savedAppConfig.store(appProps);
deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_TARGETS, previousTargets);
deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_VIRTUAL_SERVERS, previousVirtualServers);
deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_ENABLED_ATTRIBUTES, previousEnabledAttributes);
Transaction tx = deployment.prepareAppConfigChanges(deploymentContext);
// next phase is launched by prepare
span.finish();
Deployment.ApplicationDeployment deplResult = deployment.prepare(null, deploymentContext);
if (deplResult != null && !loadOnly) {
appState.ifPresent(s -> s.storeMetaData(deploymentContext));
// initialize makes its own phase as well
deployment.initialize(deplResult.appInfo, deplResult.appInfo.getSniffers(), deplResult.context);
}
ApplicationInfo appInfo = deplResult != null ? deplResult.appInfo : null;
/*
* Various deployers might have added to the downloadable or
* generated artifacts. Extract them and, if the command succeeded,
* persist both into the app properties (which will be recorded
* in domain.xml).
*/
final Artifacts downloadableArtifacts = DeploymentUtils.downloadableArtifacts(deploymentContext);
final Artifacts generatedArtifacts = DeploymentUtils.generatedArtifacts(deploymentContext);
if (report.getActionExitCode() == ActionReport.ExitCode.SUCCESS) {
try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.REGISTRATION)) {
moveAppFilesToPermanentLocation(deploymentContext, logger);
recordFileLocations(appProps);
downloadableArtifacts.record(appProps);
generatedArtifacts.record(appProps);
timeTakenToDeploy = timing.elapsed();
deploymentTimeMillis = System.currentTimeMillis();
if (tx != null) {
Application application = deploymentContext.getTransientAppMetaData("application", Application.class);
// Set the application deploy time
application.setDeploymentTime(Long.toString(timeTakenToDeploy));
application.setTimeDeployed(Long.toString(deploymentTimeMillis));
// register application information in domain.xml
deployment.registerAppInDomainXML(appInfo, deploymentContext, tx);
}
if (retrieve != null) {
retrieveArtifacts(context, downloadableArtifacts.getArtifacts(), retrieve, false, name);
}
suppInfo.setDeploymentContext(deploymentContext);
// send new event to notify the deployment process is finish
events.send(new Event<ApplicationInfo>(Deployment.DEPLOYMENT_COMMAND_FINISH, appInfo), false);
// Fix for issue 14442
// We want to report the worst subreport value.
ActionReport.ExitCode worstExitCode = ExitCode.SUCCESS;
for (ActionReport subReport : report.getSubActionsReport()) {
ActionReport.ExitCode actionExitCode = subReport.getActionExitCode();
if (actionExitCode.isWorse(worstExitCode)) {
worstExitCode = actionExitCode;
}
}
report.setActionExitCode(worstExitCode);
report.setResultType(String.class, name);
} catch (Exception e) {
// roll back the deployment and re-throw the exception
deployment.undeploy(name, deploymentContext);
deploymentContext.clean();
throw e;
}
}
} catch (Throwable e) {
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
report.setFailureCause(e);
if (e.getMessage() != null) {
report.setMessage(e.getMessage());
}
} finally {
events.unregister(this);
try {
archive.close();
} catch (IOException e) {
logger.log(Level.FINE, localStrings.getLocalString("errClosingArtifact", "Error while closing deployable artifact : ", path.getAbsolutePath()), e);
}
if (structuredTracing.isEnabled()) {
structuredTracing.print(System.out);
}
if (report.getActionExitCode().equals(ActionReport.ExitCode.SUCCESS)) {
// Set the app name in the result so that embedded deployer can retrieve it.
report.setResultType(String.class, name);
report.setMessage(localStrings.getLocalString("deploy.command.success", "Application deployed with name {0}", name));
logger.info(localStrings.getLocalString("deploy.done", "Deployment of {0} done is {1} ms at {2}", name, timeTakenToDeploy, DateFormat.getDateInstance().format(new Date(deploymentTimeMillis))));
} else if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
String errorMessage = report.getMessage();
Throwable cause = report.getFailureCause();
if (cause != null) {
String causeMessage = cause.getMessage();
if (causeMessage != null && !causeMessage.equals(errorMessage)) {
errorMessage = errorMessage + " : " + cause.getMessage();
}
logger.log(Level.SEVERE, errorMessage, cause.getCause());
}
report.setMessage(localStrings.getLocalString("deploy.errDuringDepl", "Error occur during deployment: {0}.", errorMessage));
// reset the failure cause so command framework will not try
// to print the same message again
report.setFailureCause(null);
if (expansionDir != null) {
final FileArchive arch;
try {
/*
* Open and then delete the expansion directory as
* a file archive so stale file handling can run.
*/
arch = DeploymentUtils.openAsFileArchive(expansionDir, archiveFactory);
arch.delete();
} catch (IOException ex) {
final String msg = localStrings.getLocalString("deploy.errDelRepos", "Error deleting repository directory {0}", expansionDir.getAbsolutePath());
report.failure(logger, msg, ex);
}
}
appState.map(ApplicationState::getPath).ifPresent(hotDeployService::removeApplicationState);
}
if (deploymentContext != null && !loadOnly) {
deploymentContext.postDeployClean(true);
}
appState.ifPresent(ApplicationState::close);
}
}
use of org.jvnet.hk2.config.Changed.TYPE in project Payara by payara.
the class JavaWebStartInfo method processChangeEventIfInteresting.
private void processChangeEventIfInteresting(final PropertyChangeEvent event) throws EndpointRegistrationException {
/*
* If the source is of type Application or Module and the newValue is of type
* Property then this could be a change we're interested in.
*/
final boolean isSourceApp = event.getSource() instanceof com.sun.enterprise.config.serverbeans.Application;
final boolean isSourceModule = event.getSource() instanceof com.sun.enterprise.config.serverbeans.Module;
if ((!isSourceApp && !isSourceModule) || !(event.getNewValue() instanceof Property)) {
return;
}
/*
* Make sure the property name is java-web-start-enabled.
*/
Property newPropertySetting = (Property) event.getNewValue();
if (!newPropertySetting.getName().equals(JAVA_WEB_START_ENABLED_PROPERTY_NAME)) {
return;
}
String eventSourceName;
String thisAppOrModuleName;
if (isSourceApp) {
eventSourceName = ((com.sun.enterprise.config.serverbeans.Application) event.getSource()).getName();
thisAppOrModuleName = acServerApp.registrationName();
} else {
eventSourceName = ((com.sun.enterprise.config.serverbeans.Module) event.getSource()).getName();
thisAppOrModuleName = acDesc.getModuleName();
}
if (!thisAppOrModuleName.equals(eventSourceName)) {
return;
}
/*
* At this point we know that the event applies to this app client,
* so return a Boolean carrying the newly-assigned value.
*/
final Boolean newEnabledValue = Boolean.valueOf(newPropertySetting.getValue());
final Property oldPropertySetting = (Property) event.getOldValue();
final String oldPropertyValue = (oldPropertySetting != null) ? oldPropertySetting.getValue() : null;
final Boolean oldEnabledValue = (oldPropertyValue == null ? Boolean.TRUE : Boolean.valueOf(oldPropertyValue));
/*
* Record the new value of the relevant enabled setting.
*/
if (isSourceApp) {
isJWSEnabledAtApp = newEnabledValue;
} else {
isJWSEnabledAtModule = newEnabledValue;
}
/*
* Now act on the change of state.
*/
if (!newEnabledValue.equals(oldEnabledValue)) {
if (newEnabledValue) {
start();
} else {
stop();
}
}
}
use of org.jvnet.hk2.config.Changed.TYPE in project Payara by payara.
the class UpgradeService method addProperty.
/**
* Adds a property with the specified name and value to a writable config
* object.
* @param <T> the type of the config object
* @param propName name of the property to add
* @param propValue value of the property to add
* @param owner_w the owning config object
* @return the added Property object
* @throws TransactionFailure
* @throws PropertyVetoException
*/
private <T extends PropertyBag & ConfigBeanProxy> Property addProperty(final String propName, final String propValue, final T owner_w) throws TransactionFailure, PropertyVetoException {
final Property p = owner_w.createChild(Property.class);
p.setName(propName);
p.setValue(propValue);
owner_w.getProperty().add(p);
return p;
}
Aggregations