use of org.glassfish.api.event.EventListener.Event in project Payara by payara.
the class ApplicationLoaderService method postConstruct.
/**
* Starts the application loader service.
*
* Look at the list of applications installed in our local repository
* Get a Deployer capable for each application found
* Invoke the deployer load() method for each application.
*/
public void postConstruct() {
assert env != null;
try {
logger.fine("Satisfying Optional Packages dependencies...");
InstalledLibrariesResolver.initializeInstalledLibRegistry(env.getLibPath().getAbsolutePath());
} catch (Exception e) {
logger.log(Level.WARNING, KernelLoggerInfo.exceptionOptionalDepend, e);
}
DeploymentLifecycleStatsProvider dlsp = new DeploymentLifecycleStatsProvider();
StatsProviderManager.register("deployment", PluginPoint.SERVER, "deployment/lifecycle", dlsp);
deploymentTracingEnabled = System.getProperty("org.glassfish.deployment.trace");
domain = habitat.getService(Domain.class);
/*
* Build a map that associates an application with its
* order in domain.xml. If the deployment-order attribute
* is not used for any application, then the applications
* are loaded in the order they occur in domain.xml. Also, for
* applications with the same deployment-order attribute,
* the applications are loaded in the order they occur in domain.xml.
* Otherwise, applications are loaded according to the
* deploynment-order attribute.
*/
systemApplications = domain.getSystemApplications();
for (Application systemApp : systemApplications.getApplications()) {
appOrderInfoMap.put(systemApp.getName(), Integer.valueOf(appOrder++));
}
List<Application> standaloneAdapters = applications.getApplicationsWithSnifferType(ServerTags.CONNECTOR, true);
for (Application standaloneAdapter : standaloneAdapters) {
appOrderInfoMap.put(standaloneAdapter.getName(), Integer.valueOf(appOrder++));
}
List<Application> allApplications = applications.getApplications();
for (Application app : allApplications) {
appOrderInfoMap.put(app.getName(), Integer.valueOf(appOrder++));
}
for (Application systemApp : systemApplications.getApplications()) {
// check to see if we need to load up this system application
if (Boolean.valueOf(systemApp.getDeployProperties().getProperty(ServerTags.LOAD_SYSTEM_APP_ON_STARTUP))) {
if (deployment.isAppEnabled(systemApp) || loadAppOnDAS(systemApp.getName())) {
Integer order = appOrderInfoMap.get(systemApp.getName());
ApplicationOrderInfo info = new ApplicationOrderInfo(systemApp, order);
DeploymentOrder.addApplicationDeployment(info);
}
}
}
// load standalone resource adapters first
for (Application standaloneAdapter : standaloneAdapters) {
// information is available on DAS
if (deployment.isAppEnabled(standaloneAdapter) || loadAppOnDAS(standaloneAdapter.getName())) {
DeploymentOrder.addApplicationDeployment(new ApplicationOrderInfo(standaloneAdapter, appOrderInfoMap.get(standaloneAdapter.getName()).intValue()));
}
}
// then the rest of the applications
for (Application app : allApplications) {
if (app.isStandaloneModule() && app.containsSnifferType(ServerTags.CONNECTOR)) {
continue;
}
// information is available on DAS
if (Boolean.valueOf(app.getEnabled()) || loadAppOnDAS(app.getName())) {
DeploymentOrder.addApplicationDeployment(new ApplicationOrderInfo(app, appOrderInfoMap.get(app.getName()).intValue()));
}
}
List<Deployment.ApplicationDeployment> appDeployments = new ArrayList<>();
// process the deployed applications
Iterator iter = DeploymentOrder.getApplicationDeployments();
while (iter.hasNext()) {
Application app = (Application) iter.next();
ApplicationRef appRef = server.getApplicationRef(app.getName());
if (appRef != null) {
// Does the application need to be run on this instance?
appDeployments.addAll(processApplication(app, appRef));
}
}
// does the user want us to run a particular application
String defaultParam = env.getStartupContext().getArguments().getProperty("default");
if (defaultParam != null) {
initializeRuntimeDependencies();
File sourceFile;
if (defaultParam.equals(".")) {
sourceFile = new File(System.getProperty("user.dir"));
} else {
sourceFile = new File(defaultParam);
}
if (sourceFile.exists()) {
sourceFile = sourceFile.getAbsoluteFile();
ReadableArchive sourceArchive = null;
try {
sourceArchive = archiveFactoryProvider.get().openArchive(sourceFile);
DeployCommandParameters parameters = new DeployCommandParameters(sourceFile);
parameters.name = sourceFile.getName();
parameters.enabled = Boolean.TRUE;
parameters.origin = DeployCommandParameters.Origin.deploy;
ActionReport report = new HTMLActionReporter();
if (!sourceFile.isDirectory()) {
// ok we need to explode the directory somwhere and remember to delete it on shutdown
final File tmpFile = File.createTempFile(sourceFile.getName(), "");
final String path = tmpFile.getAbsolutePath();
if (!tmpFile.delete()) {
logger.log(Level.WARNING, KernelLoggerInfo.cantDeleteTempFile, path);
}
File tmpDir = new File(path);
FileUtils.deleteOnExit(tmpDir);
events.register(new org.glassfish.api.event.EventListener() {
public void event(Event event) {
if (event.is(EventTypes.SERVER_SHUTDOWN)) {
if (tmpFile.exists()) {
FileUtils.whack(tmpFile);
}
}
}
});
if (tmpDir.mkdirs()) {
ArchiveHandler handler = deployment.getArchiveHandler(sourceArchive);
final String appName = handler.getDefaultApplicationName(sourceArchive);
DeploymentContextImpl dummyContext = new DeploymentContextImpl(report, logger, sourceArchive, parameters, env);
handler.expand(sourceArchive, archiveFactoryProvider.get().createArchive(tmpDir), dummyContext);
sourceArchive = archiveFactoryProvider.get().openArchive(tmpDir);
logger.log(Level.INFO, KernelLoggerInfo.sourceNotDirectory, tmpDir.getAbsolutePath());
parameters.name = appName;
}
}
ExtendedDeploymentContext depContext = deployment.getBuilder(logger, parameters, report).source(sourceArchive).build();
Deployment.ApplicationDeployment appDeployment = deployment.prepare(null, depContext);
if (appDeployment == null) {
logger.log(Level.SEVERE, KernelLoggerInfo.cantFindApplicationInfo, sourceFile.getAbsolutePath());
} else {
appDeployments.add(appDeployment);
}
} catch (RuntimeException | IOException e) {
logger.log(Level.SEVERE, KernelLoggerInfo.deployException, e);
} finally {
if (sourceArchive != null) {
try {
sourceArchive.close();
} catch (IOException ioe) {
// ignore
}
}
}
}
}
events.send(new Event<>(Deployment.ALL_APPLICATIONS_LOADED, null), false);
for (Deployment.ApplicationDeployment depl : appDeployments) {
deployment.initialize(depl.appInfo, depl.appInfo.getSniffers(), depl.context);
}
events.send(new Event<>(Deployment.ALL_APPLICATIONS_PROCESSED, null));
}
use of org.glassfish.api.event.EventListener.Event in project Payara by payara.
the class ApplicationLifecycle method prepare.
@Override
public ApplicationDeployment prepare(Collection<? extends Sniffer> sniffers, final ExtendedDeploymentContext context) {
StructuredDeploymentTracing tracing = StructuredDeploymentTracing.load(context);
DeploymentSpan eventSpan = tracing.startSpan(DeploymentTracing.AppStage.PROCESS_EVENTS, Deployment.DEPLOYMENT_START.type());
events.send(new Event<>(Deployment.DEPLOYMENT_START, context), false);
eventSpan.close();
currentDeploymentContext.get().push(context);
final ActionReport report = context.getActionReport();
final DeployCommandParameters commandParams = context.getCommandParameters(DeployCommandParameters.class);
final String appName = commandParams.name();
ApplicationInfo appInfo;
Optional<ApplicationState> appState = hotDeployService.getApplicationState(context);
final ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
ProgressTracker tracker = new ProgressTracker() {
@Override
public void actOn(Logger logger) {
// loaded but may not be started. Issue 18263
for (EngineRef module : get("loaded", EngineRef.class)) {
try {
module.stop(context);
} catch (Exception e) {
// ignore
}
}
try {
PreDestroy.class.cast(context).preDestroy();
} catch (Exception e) {
// ignore
}
for (EngineRef module : get("loaded", EngineRef.class)) {
try {
module.unload(context);
} catch (Exception e) {
// ignore
}
}
try {
ApplicationInfo appInfo = appRegistry.get(appName);
if (appInfo != null) {
// send the event to close necessary resources
events.send(new Event<>(Deployment.APPLICATION_DISABLED, appInfo));
}
} catch (Exception e) {
// ignore
}
for (EngineRef module : get("prepared", EngineRef.class)) {
try {
module.clean(context);
} catch (Exception e) {
// ignore
}
}
if (!commandParams.keepfailedstubs) {
try {
context.clean();
} catch (Exception e) {
// ignore
}
}
appRegistry.remove(appName);
}
};
try (DeploymentSpan topSpan = tracing.startSpan(DeploymentTracing.AppStage.PREPARE);
SpanSequence span = tracing.startSequence(DeploymentTracing.AppStage.PREPARE, "ArchiveMetadata")) {
if (commandParams.origin == OpsParams.Origin.deploy && appRegistry.get(appName) != null && !commandParams.hotDeploy) {
report.setMessage(localStrings.getLocalString("appnamenotunique", "Application name {0} is already in use. Please pick a different name.", appName));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return null;
}
// defined virtual servers minus __asadmin on that target
if (commandParams.virtualservers == null) {
commandParams.virtualservers = DeploymentUtils.getVirtualServers(commandParams.target, env, domain);
}
if (commandParams.enabled == null) {
commandParams.enabled = Boolean.TRUE;
}
if (commandParams.altdd != null) {
context.getSource().addArchiveMetaData(DeploymentProperties.ALT_DD, commandParams.altdd);
}
if (commandParams.runtimealtdd != null) {
context.getSource().addArchiveMetaData(DeploymentProperties.RUNTIME_ALT_DD, commandParams.runtimealtdd);
}
context.addTransientAppMetaData(ExtendedDeploymentContext.TRACKER, tracker);
context.setPhase(DeploymentContextImpl.Phase.PREPARE);
span.start("ArchiveHandler");
ArchiveHandler handler = context.getArchiveHandler();
if (handler == null) {
handler = getArchiveHandler(context.getSource(), commandParams.type);
context.setArchiveHandler(handler);
}
if (handler == null) {
report.setMessage(localStrings.getLocalString("unknownarchivetype", "Archive type of {0} was not recognized", context.getSourceDir()));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return null;
}
span.start(DeploymentTracing.AppStage.CLASS_SCANNING);
if (handler.requiresAnnotationScanning(context.getSource())) {
getDeployableTypes(context);
}
span.finish();
// is that some container do not support to be restarted.
if (sniffers != null && logger.isLoggable(Level.FINE)) {
for (Sniffer sniffer : sniffers) {
logger.log(FINE, "Before Sorting{0}", sniffer.getModuleType());
}
}
span.start(DeploymentTracing.AppStage.PREPARE, "Sniffer");
sniffers = getSniffers(handler, sniffers, context);
final Collection<? extends Sniffer> selectedSniffers = sniffers;
appState.ifPresent(s -> s.setSniffers(selectedSniffers));
span.start(DeploymentTracing.AppStage.PREPARE, "ClassLoaderHierarchy");
ClassLoaderHierarchy clh = habitat.getService(ClassLoaderHierarchy.class);
span.start(DeploymentTracing.AppStage.PREPARE, "ClassLoader");
context.createDeploymentClassLoader(clh, handler);
events.send(new Event<>(Deployment.AFTER_DEPLOYMENT_CLASSLOADER_CREATION, context), false);
Thread.currentThread().setContextClassLoader(context.getClassLoader());
span.start(DeploymentTracing.AppStage.PREPARE, "Container");
final List<EngineInfo> sortedEngineInfos;
if (appState.map(ApplicationState::getEngineInfos).isPresent()) {
sortedEngineInfos = appState.get().getEngineInfos();
loadDeployers(sortedEngineInfos.stream().collect(toMap(EngineInfo::getDeployer, Function.identity())), context);
} else {
sortedEngineInfos = setupContainerInfos(handler, sniffers, context);
appState.ifPresent(s -> s.setEngineInfos(sortedEngineInfos));
}
// a bit more is happening here, but I cannot quite describe it yet
span.start(DeploymentTracing.AppStage.CREATE_CLASSLOADER);
if (sortedEngineInfos.isEmpty()) {
throw new DeploymentException(localStrings.getLocalString("unknowncontainertype", "There is no installed container capable of handling this application {0}", context.getSource().getName()));
}
if (logger.isLoggable(Level.FINE)) {
for (EngineInfo info : sortedEngineInfos) {
logger.log(FINE, "After Sorting {0}", info.getSniffer().getModuleType());
}
}
// create a temporary application info to hold metadata
// so the metadata could be accessed at classloader
// construction time through ApplicationInfo
ApplicationInfo tempAppInfo = new ApplicationInfo(events, context.getSource(), appName);
for (Object m : context.getModuleMetadata()) {
tempAppInfo.addMetaData(m);
}
tempAppInfo.setIsJavaEEApp(sortedEngineInfos);
// set the flag on the archive to indicate whether it's
// a JavaEE archive or not
context.getSource().setExtraData(Boolean.class, tempAppInfo.isJavaEEApp());
appRegistry.add(appName, tempAppInfo);
try {
notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.PREPARE, context);
} catch (Throwable interceptorException) {
report.failure(logger, "Exception while invoking the lifecycle interceptor", null);
report.setFailureCause(interceptorException);
logger.log(SEVERE, KernelLoggerInfo.lifecycleException, interceptorException);
tracker.actOn(logger);
return null;
}
events.send(new Event<>(Deployment.DEPLOYMENT_BEFORE_CLASSLOADER_CREATION, context), false);
context.createApplicationClassLoader(clh, handler);
tempAppInfo.setAppClassLoader(context.getFinalClassLoader());
events.send(new Event<>(Deployment.AFTER_APPLICATION_CLASSLOADER_CREATION, context), false);
// this is a first time deployment as opposed as load following an unload event,
// we need to create the application info
// todo : we should come up with a general Composite API solution
final ModuleInfo moduleInfo;
try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.PREPARE, "Module")) {
if (appState.map(ApplicationState::getModuleInfo).isPresent()) {
moduleInfo = appState.get().getModuleInfo();
moduleInfo.reset();
} else {
moduleInfo = prepareModule(sortedEngineInfos, appName, context, tracker);
appState.ifPresent(s -> s.setModuleInfo(moduleInfo));
}
// Now that the prepare phase is done, any artifacts
// should be available. Go ahead and create the
// downloadable client JAR. We want to do this now, or
// at least before the load and start phases, because
// (for example) the app client deployer start phase
// needs to find all generated files when it runs.
final ClientJarWriter cjw = new ClientJarWriter(context);
cjw.run();
} catch (Throwable prepareException) {
report.failure(logger, "Exception while preparing the app", null);
report.setFailureCause(prepareException);
logger.log(SEVERE, KernelLoggerInfo.lifecycleException, prepareException);
tracker.actOn(logger);
return null;
}
span.start(DeploymentTracing.AppStage.PROCESS_EVENTS, Deployment.APPLICATION_PREPARED.type());
// is not a composite module.
if (appState.map(ApplicationState::getApplicationInfo).isPresent()) {
appInfo = appState.get().getApplicationInfo();
appInfo.reset(context.getSource());
for (Object metadata : context.getModuleMetadata()) {
moduleInfo.addMetaData(metadata);
appInfo.addMetaData(metadata);
}
} else if ((appInfo = context.getModuleMetaData(ApplicationInfo.class)) == null) {
ApplicationInfo applicationInfo = new ApplicationInfo(events, context.getSource(), appName);
appInfo = applicationInfo;
appInfo.addModule(moduleInfo);
appState.ifPresent(s -> s.setApplicationInfo(applicationInfo));
for (Object metadata : context.getModuleMetadata()) {
moduleInfo.addMetaData(metadata);
appInfo.addMetaData(metadata);
}
} else {
for (EngineRef ref : moduleInfo.getEngineRefs()) {
appInfo.add(ref);
}
}
// remove the temp application info from the registry
// first, then register the real one
appRegistry.remove(appName);
appInfo.setIsJavaEEApp(sortedEngineInfos);
appRegistry.add(appName, appInfo);
notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.PREPARE, context);
// send the APPLICATION_PREPARED event
// set the phase and thread context classloader properly
// before sending the event
context.setPhase(DeploymentContextImpl.Phase.PREPARED);
Thread.currentThread().setContextClassLoader(context.getClassLoader());
appInfo.setAppClassLoader(context.getClassLoader());
appState.ifPresent(s -> s.setApplicationClassLoader(context.getClassLoader()));
events.send(new Event<>(Deployment.APPLICATION_PREPARED, context), false);
if (loadOnCurrentInstance(context)) {
appInfo.setLibraries(commandParams.libraries());
try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.LOAD)) {
notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.LOAD, context);
appInfo.load(context, tracker);
notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.LOAD, context);
} catch (Throwable loadException) {
logger.log(SEVERE, KernelLoggerInfo.lifecycleException, loadException);
report.failure(logger, "Exception while loading the app", null);
report.setFailureCause(loadException);
tracker.actOn(logger);
return null;
}
}
} catch (DeploymentException de) {
report.failure(logger, de.getMessage());
tracker.actOn(logger);
return null;
} catch (Exception e) {
report.failure(logger, localStrings.getLocalString("error.deploying.app", "Exception while deploying the app [{0}]", appName), null);
report.setFailureCause(e);
logger.log(SEVERE, KernelLoggerInfo.lifecycleException, e);
tracker.actOn(logger);
return null;
} finally {
Thread.currentThread().setContextClassLoader(currentCL);
if (report.getActionExitCode() != ActionReport.ExitCode.SUCCESS) {
context.postDeployClean(false);
events.send(new Event<>(Deployment.DEPLOYMENT_FAILURE, context));
}
}
ApplicationDeployment depl = new ApplicationDeployment(appInfo, context);
appRegistry.addTransient(depl);
return depl;
}
use of org.glassfish.api.event.EventListener.Event in project Payara by payara.
the class ApplicationLifecycle method undeploy.
@Override
public void undeploy(String appName, ExtendedDeploymentContext context) {
ActionReport report = context.getActionReport();
UndeployCommandParameters params = context.getCommandParameters(UndeployCommandParameters.class);
ApplicationInfo info = appRegistry.get(appName);
if (info == null) {
report.failure(context.getLogger(), "Application " + appName + " not registered", null);
events.send(new Event(Deployment.UNDEPLOYMENT_FAILURE, context));
return;
}
events.send(new Event(Deployment.UNDEPLOYMENT_START, info));
// we unconditionally unload the application, even if it is not loaded, because we must clean the
// application, especially the classloaders need to be closed to release file handles
unload(info, context);
if (report != null && report.getActionExitCode().equals(ActionReport.ExitCode.SUCCESS)) {
events.send(new Event(Deployment.UNDEPLOYMENT_SUCCESS, context));
deploymentLifecycleProbeProvider.applicationUndeployedEvent(appName, getApplicationType(info));
} else {
events.send(new Event(Deployment.UNDEPLOYMENT_FAILURE, context));
}
appRegistry.remove(appName);
}
use of org.glassfish.api.event.EventListener.Event in project Payara by payara.
the class AppServerStartup method postStartupJob.
/**
* @return True if started successfully, false otherwise
*/
private boolean postStartupJob() {
LinkedList<Future<Result<Thread>>> futures = appInstanceListener.getFutures();
env.setStatus(ServerEnvironment.Status.starting);
events.send(new Event(EventTypes.SERVER_STARTUP), false);
// finally let's calculate our starting times
long nowTime = System.currentTimeMillis();
logger.log(Level.INFO, KernelLoggerInfo.startupEndMessage, new Object[] { Version.getVersion(), Version.getBuildVersion(), platform, (platformInitTime - context.getCreationTime()), (nowTime - platformInitTime), nowTime - context.getCreationTime() });
printModuleStatus(systemRegistry, level);
String wallClockStart = System.getProperty("WALL_CLOCK_START");
if (wallClockStart != null) {
try {
// it will only be set when called from AsadminMain and the env. variable AS_DEBUG is set to true
long realstart = Long.parseLong(wallClockStart);
logger.log(Level.INFO, KernelLoggerInfo.startupTotalTime, (System.currentTimeMillis() - realstart));
} catch (Exception e) {
// do nothing.
}
}
for (Future<Result<Thread>> future : futures) {
try {
try {
// wait for an eventual status, otherwise ignore
if (future.get(3, TimeUnit.SECONDS).isFailure()) {
final Throwable t = future.get().exception();
logger.log(Level.SEVERE, KernelLoggerInfo.startupFatalException, t);
shutdown();
return false;
}
} catch (TimeoutException e) {
logger.log(Level.WARNING, KernelLoggerInfo.startupWaitTimeout, e);
}
} catch (Throwable t) {
logger.log(Level.SEVERE, KernelLoggerInfo.startupException, t);
}
}
env.setStatus(ServerEnvironment.Status.started);
events.send(new Event(EventTypes.SERVER_READY), false);
pidWriter.writePidFile();
return true;
}
use of org.glassfish.api.event.EventListener.Event in project Payara by payara.
the class ApplicationLifecycle method initialize.
@Override
public void initialize(ApplicationInfo appInfo, Collection<? extends Sniffer> sniffers, ExtendedDeploymentContext context) {
if (appInfo == null) {
return;
}
appRegistry.removeTransient(appInfo.getName());
final ActionReport report = context.getActionReport();
ProgressTracker tracker = context.getTransientAppMetaData(ExtendedDeploymentContext.TRACKER, ProgressTracker.class);
StructuredDeploymentTracing tracing = StructuredDeploymentTracing.load(context);
// associated engines and the application info is created and registered
if (loadOnCurrentInstance(context)) {
try (SpanSequence span = tracing.startSequence(DeploymentTracing.AppStage.INITIALIZE)) {
notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.START, context);
appInfo.initialize();
appInfo.getModuleInfos().forEach(moduleInfo -> moduleInfo.getEngineRefs().forEach(engineRef -> tracker.add("initialized", EngineRef.class, engineRef)));
span.start(DeploymentTracing.AppStage.START);
appInfo.start(context, tracker);
notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.START, context);
} catch (Throwable loadException) {
logger.log(SEVERE, KernelLoggerInfo.lifecycleException, loadException);
report.failure(logger, "Exception while loading the app", null);
report.setFailureCause(loadException);
tracker.actOn(logger);
} finally {
context.postDeployClean(false);
if (report.getActionExitCode() == ActionReport.ExitCode.FAILURE) {
// warning status code is not a failure
events.send(new Event<>(Deployment.DEPLOYMENT_FAILURE, context));
} else {
events.send(new Event<>(Deployment.DEPLOYMENT_SUCCESS, appInfo));
}
}
currentDeploymentContext.get().pop();
}
}
Aggregations