Search in sources :

Example 21 with TYPE

use of org.jvnet.hk2.config.Changed.TYPE in project Payara by payara.

the class CreateMessageSecurityProvider method execute.

/**
 * Executes the command with the command parameters passed as Properties
 * where the keys are parameter names and the values the parameter values
 *
 * @param context information
 */
@Override
public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    List<MessageSecurityConfig> mscs = secService.getMessageSecurityConfig();
    // Let's find the correct MessageSecurityConfig. As of now,
    // there can be only two of them - one for SOAP and one for
    // HttpServlet
    MessageSecurityConfig msgSecCfg = null;
    for (MessageSecurityConfig msc : mscs) {
        if (msc.getAuthLayer().equals(authLayer)) {
            msgSecCfg = msc;
        }
    }
    // then, add a new provider config under it provided it is not duplicate
    if (msgSecCfg != null) {
        // check if there exists a provider config by the
        // specified provider name; if so return failure.
        List<ProviderConfig> pcs = msgSecCfg.getProviderConfig();
        for (ProviderConfig pc : pcs) {
            if (pc.getProviderId().equals(providerId)) {
                report.setMessage(localStrings.getLocalString("create.message.security.provider.duplicatefound", "Message security provider named {0} exists. " + "Cannot add duplicate.", providerId));
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                return;
            }
        }
        // No duplicate message security providers found. So add one.
        try {
            ConfigSupport.apply(new SingleConfigCode<MessageSecurityConfig>() {

                public Object run(MessageSecurityConfig param) throws PropertyVetoException, TransactionFailure {
                    ProviderConfig newPC = param.createChild(ProviderConfig.class);
                    populateProviderConfigElement(newPC);
                    param.getProviderConfig().add(newPC);
                    // security config object
                    if (isDefaultProvider) {
                        if (providerType.equals(SERVER) || providerType.equals(CLIENT_SERVER)) {
                            param.setDefaultProvider(providerId);
                        }
                        if (providerType.equals(CLIENT) || providerType.equals(CLIENT_SERVER)) {
                            param.setDefaultClientProvider(providerId);
                        }
                    }
                    return newPC;
                }
            }, msgSecCfg);
        } catch (TransactionFailure e) {
            report.setMessage(localStrings.getLocalString("create.message.security.provider.fail", "Creation of message security provider named {0} failed", providerId));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setFailureCause(e);
            return;
        }
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        report.setMessage(localStrings.getLocalString("create.message.security.provider.success", "Creation of message security provider named {0} completed " + "successfully", providerId));
    } else // Now if there is NO message security config for this type of layer
    // then, first add a message security config for the layer and then
    // add a provider config under this message security config
    {
        try {
            ConfigSupport.apply(new SingleConfigCode<SecurityService>() {

                public Object run(SecurityService param) throws PropertyVetoException, TransactionFailure {
                    MessageSecurityConfig newMSC = param.createChild(MessageSecurityConfig.class);
                    newMSC.setAuthLayer(authLayer);
                    param.getMessageSecurityConfig().add(newMSC);
                    ProviderConfig newPC = newMSC.createChild(ProviderConfig.class);
                    populateProviderConfigElement(newPC);
                    newMSC.getProviderConfig().add(newPC);
                    // security config object
                    if (isDefaultProvider) {
                        if (providerType.equals(SERVER) || providerType.equals(CLIENT_SERVER)) {
                            newMSC.setDefaultProvider(providerId);
                        }
                        if (providerType.equals(CLIENT) || providerType.equals(CLIENT_SERVER)) {
                            newMSC.setDefaultClientProvider(providerId);
                        }
                    }
                    return newMSC;
                }
            }, secService);
        } catch (TransactionFailure e) {
            report.setMessage(localStrings.getLocalString("create.message.security.provider.fail", "Creation of message security provider named {0} failed", providerId));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setFailureCause(e);
            return;
        }
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
    /* report.setMessage(localStrings.getLocalString(
                "create.message.security.provider.success",
                "Creation of message security provider named {0} completed " +
                "successfully", providerId));  */
    }
}
Also used : PropertyVetoException(java.beans.PropertyVetoException) TransactionFailure(org.jvnet.hk2.config.TransactionFailure) ProviderConfig(com.sun.enterprise.config.serverbeans.ProviderConfig) SecurityService(com.sun.enterprise.config.serverbeans.SecurityService) MessageSecurityConfig(com.sun.enterprise.config.serverbeans.MessageSecurityConfig) ActionReport(org.glassfish.api.ActionReport)

Example 22 with TYPE

use of org.jvnet.hk2.config.Changed.TYPE 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;
}
Also used : StructuredDeploymentTracing(org.glassfish.internal.deployment.analysis.StructuredDeploymentTracing) ApplicationMetaDataProvider(org.glassfish.api.deployment.ApplicationMetaDataProvider) BufferedInputStream(java.io.BufferedInputStream) Event(org.glassfish.api.event.EventListener.Event) KernelLoggerInfo(org.glassfish.kernel.KernelLoggerInfo) ParsingConfig(org.glassfish.hk2.classmodel.reflect.util.ParsingConfig) TraceContext(org.glassfish.internal.deployment.analysis.TraceContext) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) ServerEnvironment(org.glassfish.api.admin.ServerEnvironment) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) Property(org.jvnet.hk2.config.types.Property) HotDeployService(fish.payara.nucleus.hotdeploy.HotDeployService) DeploymentTracing(org.glassfish.internal.deployment.DeploymentTracing) ParameterMapExtractor(org.glassfish.common.util.admin.ParameterMapExtractor) WARNING(java.util.logging.Level.WARNING) CommonModelRegistry(org.glassfish.hk2.classmodel.reflect.util.CommonModelRegistry) com.sun.enterprise.config.serverbeans(com.sun.enterprise.config.serverbeans) MultiException(org.glassfish.hk2.api.MultiException) Service(org.jvnet.hk2.annotations.Service) Container(org.glassfish.api.container.Container) DeploymentException(org.glassfish.deployment.common.DeploymentException) ServiceLocator(org.glassfish.hk2.api.ServiceLocator) ZipOutputStream(java.util.zip.ZipOutputStream) DeploymentContextImpl(org.glassfish.deployment.common.DeploymentContextImpl) ProgressTracker(org.glassfish.internal.data.ProgressTracker) java.util(java.util) Dom(org.jvnet.hk2.config.Dom) OpsParams(org.glassfish.api.deployment.OpsParams) ClassLoaderHierarchy(org.glassfish.internal.api.ClassLoaderHierarchy) EngineRef(org.glassfish.internal.data.EngineRef) BufferedOutputStream(java.io.BufferedOutputStream) ArchiveFactory(com.sun.enterprise.deploy.shared.ArchiveFactory) ArchiveDetector(org.glassfish.api.deployment.archive.ArchiveDetector) LocalStringManagerImpl(com.sun.enterprise.util.LocalStringManagerImpl) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) VersioningUtils(org.glassfish.deployment.versioning.VersioningUtils) ApplicationLifecycleInterceptor(org.glassfish.internal.deployment.ApplicationLifecycleInterceptor) Sniffer(org.glassfish.api.container.Sniffer) WritableArchive(org.glassfish.api.deployment.archive.WritableArchive) ApplicationName(org.glassfish.api.admin.config.ApplicationName) Named(javax.inject.Named) PreDestroy(org.glassfish.hk2.api.PreDestroy) DeploymentProperties(org.glassfish.deployment.common.DeploymentProperties) ApplicationConfigInfo(org.glassfish.deployment.common.ApplicationConfigInfo) ServerEnvironmentImpl(org.glassfish.server.ServerEnvironmentImpl) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) SingleConfigCode(org.jvnet.hk2.config.SingleConfigCode) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ConfigSupport(org.jvnet.hk2.config.ConfigSupport) DeploymentSpan(org.glassfish.internal.deployment.analysis.DeploymentSpan) File(java.io.File) PostConstruct(org.glassfish.hk2.api.PostConstruct) Parser(org.glassfish.hk2.classmodel.reflect.Parser) MetaData(org.glassfish.api.deployment.MetaData) EngineInfo(org.glassfish.internal.data.EngineInfo) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ApplicationRegistry(org.glassfish.internal.data.ApplicationRegistry) FileUtils(com.sun.enterprise.util.io.FileUtils) ResourceLocator(org.glassfish.hk2.classmodel.reflect.util.ResourceLocator) SpanSequence(org.glassfish.internal.deployment.analysis.SpanSequence) Events(org.glassfish.api.event.Events) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) PropertyVetoException(java.beans.PropertyVetoException) ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) Collectors.toMap(java.util.stream.Collectors.toMap) TransactionFailure(org.jvnet.hk2.config.TransactionFailure) URI(java.net.URI) ThreadFactory(java.util.concurrent.ThreadFactory) ZipEntry(java.util.zip.ZipEntry) ContainerRegistry(org.glassfish.internal.data.ContainerRegistry) RetryableException(org.jvnet.hk2.config.RetryableException) ClientJarWriter(org.glassfish.deployment.common.ClientJarWriter) ParameterMap(org.glassfish.api.admin.ParameterMap) Logger(java.util.logging.Logger) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ApplicationState(fish.payara.nucleus.hotdeploy.ApplicationState) DeploymentLifecycleProbeProvider(org.glassfish.deployment.monitor.DeploymentLifecycleProbeProvider) UndeployCommandParameters(org.glassfish.api.deployment.UndeployCommandParameters) DeploymentGroup(fish.payara.enterprise.config.serverbeans.DeploymentGroup) Deployment(org.glassfish.internal.deployment.Deployment) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) INFO(java.util.logging.Level.INFO) Singleton(javax.inject.Singleton) Function(java.util.function.Function) Level(java.util.logging.Level) SEVERE(java.util.logging.Level.SEVERE) ActionReport(org.glassfish.api.ActionReport) Inject(javax.inject.Inject) PayaraExecutorService(fish.payara.nucleus.executorservice.PayaraExecutorService) ExecutorService(java.util.concurrent.ExecutorService) Types(org.glassfish.hk2.classmodel.reflect.Types) FINE(java.util.logging.Level.FINE) Deployer(org.glassfish.api.deployment.Deployer) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) DeploymentUtils(org.glassfish.deployment.common.DeploymentUtils) FileInputStream(java.io.FileInputStream) ModuleInfo(org.glassfish.internal.data.ModuleInfo) TimeUnit(java.util.concurrent.TimeUnit) VirtualizationEnv(org.glassfish.api.virtualization.VirtualizationEnv) ConfigBean(org.jvnet.hk2.config.ConfigBean) Transaction(org.jvnet.hk2.config.Transaction) CompositeHandler(org.glassfish.api.deployment.archive.CompositeHandler) ParsingContext(org.glassfish.hk2.classmodel.reflect.ParsingContext) InputStream(java.io.InputStream) ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) ProgressTracker(org.glassfish.internal.data.ProgressTracker) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) ClassLoaderHierarchy(org.glassfish.internal.api.ClassLoaderHierarchy) EngineInfo(org.glassfish.internal.data.EngineInfo) StructuredDeploymentTracing(org.glassfish.internal.deployment.analysis.StructuredDeploymentTracing) SpanSequence(org.glassfish.internal.deployment.analysis.SpanSequence) ApplicationState(fish.payara.nucleus.hotdeploy.ApplicationState) ClientJarWriter(org.glassfish.deployment.common.ClientJarWriter) Sniffer(org.glassfish.api.container.Sniffer) EngineRef(org.glassfish.internal.data.EngineRef) MultiException(org.glassfish.hk2.api.MultiException) DeploymentException(org.glassfish.deployment.common.DeploymentException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) RetryableException(org.jvnet.hk2.config.RetryableException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) ModuleInfo(org.glassfish.internal.data.ModuleInfo) PreDestroy(org.glassfish.hk2.api.PreDestroy) DeploymentException(org.glassfish.deployment.common.DeploymentException) DeploymentSpan(org.glassfish.internal.deployment.analysis.DeploymentSpan)

Example 23 with TYPE

use of org.jvnet.hk2.config.Changed.TYPE in project Payara by payara.

the class ApplicationLifecycle method setupContainerInfos.

/**
 * set up containers and prepare the sorted ModuleInfos
 * @param handler
 * @param sniffers
 * @param context
 * @return
 * @throws java.lang.Exception
 */
@Override
public List<EngineInfo> setupContainerInfos(final ArchiveHandler handler, Collection<? extends Sniffer> sniffers, DeploymentContext context) throws Exception {
    final ActionReport report = context.getActionReport();
    StructuredDeploymentTracing tracing = StructuredDeploymentTracing.load(context);
    Map<Deployer, EngineInfo> containerInfosByDeployers = new LinkedHashMap<>();
    for (Sniffer sniffer : sniffers) {
        if (sniffer.getContainersNames() == null || sniffer.getContainersNames().length == 0) {
            report.failure(logger, "no container associated with application of type : " + sniffer.getModuleType(), null);
            throw new DeploymentException(localStrings.getLocalString("unknowncontainertype", "There is no installed container capable of handling this application {0}", context.getSource().getName()));
        }
        final String containerName = sniffer.getContainersNames()[0];
        EngineInfo engineInfo = startEngine(context, sniffer, containerName);
        Deployer deployer = startDeployer(context, containerName, engineInfo);
        containerInfosByDeployers.put(deployer, engineInfo);
    }
    // all containers that have recognized parts of the application being deployed
    // have now been successfully started. Start the deployment process.
    List<EngineInfo> sortedEngineInfos = new ArrayList<>();
    // ok everything is satisfied, just a matter of running things in order
    List<Deployer> orderedDeployers = loadDeployers(containerInfosByDeployers, context);
    // now load metadata from deployers.
    for (Deployer deployer : orderedDeployers) {
        if (logger.isLoggable(Level.FINE)) {
            logger.log(FINE, "Ordered Deployer {0}", deployer.getClass());
        }
        final MetaData metadata = deployer.getMetaData();
        EngineInfo engineInfo = containerInfosByDeployers.get(deployer);
        try (DeploymentSpan span = tracing.startSpan(TraceContext.Level.CONTAINER, engineInfo.getSniffer().getModuleType(), DeploymentTracing.AppStage.PREPARE, "MetaData")) {
            if (metadata != null) {
                if (metadata.provides() == null || metadata.provides().length == 0) {
                    deployer.loadMetaData(null, context);
                } else {
                    for (Class<?> provide : metadata.provides()) {
                        if (context.getModuleMetaData(provide) == null) {
                            context.addModuleMetaData(deployer.loadMetaData(provide, context));
                        } else {
                            deployer.loadMetaData(null, context);
                        }
                    }
                }
            } else {
                deployer.loadMetaData(null, context);
            }
        } catch (Exception e) {
            report.failure(logger, "Exception while invoking " + deployer.getClass() + " prepare method", e);
            throw e;
        }
        sortedEngineInfos.add(containerInfosByDeployers.get(deployer));
    }
    return sortedEngineInfos;
}
Also used : Sniffer(org.glassfish.api.container.Sniffer) ActionReport(org.glassfish.api.ActionReport) MultiException(org.glassfish.hk2.api.MultiException) DeploymentException(org.glassfish.deployment.common.DeploymentException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) RetryableException(org.jvnet.hk2.config.RetryableException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) EngineInfo(org.glassfish.internal.data.EngineInfo) MetaData(org.glassfish.api.deployment.MetaData) StructuredDeploymentTracing(org.glassfish.internal.deployment.analysis.StructuredDeploymentTracing) DeploymentException(org.glassfish.deployment.common.DeploymentException) DeploymentSpan(org.glassfish.internal.deployment.analysis.DeploymentSpan) Deployer(org.glassfish.api.deployment.Deployer)

Example 24 with TYPE

use of org.jvnet.hk2.config.Changed.TYPE in project Payara by payara.

the class GetHealthCheckConfiguration method addThresholdDiagnosticsCheckerExtraProps.

private void addThresholdDiagnosticsCheckerExtraProps(Properties thresholdDiagnosticsExtraProps, ThresholdDiagnosticsChecker thresholdDiagnosticsChecker) {
    Map<String, Object> extraPropsMap = new HashMap<>(8);
    extraPropsMap.put("checkerName", thresholdDiagnosticsChecker.getName());
    extraPropsMap.put("enabled", thresholdDiagnosticsChecker.getEnabled());
    extraPropsMap.put("time", thresholdDiagnosticsChecker.getTime());
    extraPropsMap.put("unit", thresholdDiagnosticsChecker.getUnit());
    extraPropsMap.put("addToMicroProfileHealth", thresholdDiagnosticsChecker.getAddToMicroProfileHealth());
    if (thresholdDiagnosticsChecker.getProperty(THRESHOLD_CRITICAL) != null) {
        extraPropsMap.put("thresholdCritical", thresholdDiagnosticsChecker.getProperty(THRESHOLD_CRITICAL).getValue());
    }
    if (thresholdDiagnosticsChecker.getProperty(THRESHOLD_WARNING) != null) {
        extraPropsMap.put("thresholdWarning", thresholdDiagnosticsChecker.getProperty(THRESHOLD_WARNING).getValue());
    }
    if (thresholdDiagnosticsChecker.getProperty(THRESHOLD_GOOD) != null) {
        extraPropsMap.put("thresholdGood", thresholdDiagnosticsChecker.getProperty(THRESHOLD_GOOD).getValue());
    }
    // Get the checker type
    ConfigView view = ConfigSupport.getImpl(thresholdDiagnosticsChecker);
    CheckerConfigurationType annotation = view.getProxyType().getAnnotation(CheckerConfigurationType.class);
    // Add the extraPropsMap as a property with a name matching its checker type
    switch(annotation.type()) {
        case CONNECTION_POOL:
            thresholdDiagnosticsExtraProps.put(connectionPoolPropertyName, extraPropsMap);
            break;
        case CPU_USAGE:
            thresholdDiagnosticsExtraProps.put(cpuUsagePropertyName, extraPropsMap);
            break;
        case GARBAGE_COLLECTOR:
            thresholdDiagnosticsExtraProps.put(garbageCollectorPropertyName, extraPropsMap);
            break;
        case HEAP_MEMORY_USAGE:
            thresholdDiagnosticsExtraProps.put(heapMemoryUsagePropertyName, extraPropsMap);
            break;
        case MACHINE_MEMORY_USAGE:
            thresholdDiagnosticsExtraProps.put(machineMemoryUsagePropertyName, extraPropsMap);
            break;
        case STUCK_THREAD:
            thresholdDiagnosticsExtraProps.put(stuckThreadsPropertyName, extraPropsMap);
            break;
    }
}
Also used : HashMap(java.util.HashMap) ConfigView(org.jvnet.hk2.config.ConfigView) CheckerConfigurationType(fish.payara.nucleus.healthcheck.configuration.CheckerConfigurationType)

Example 25 with TYPE

use of org.jvnet.hk2.config.Changed.TYPE in project Payara by payara.

the class DynamicConfigListener method changed.

@Override
public synchronized UnprocessedChangeEvents changed(final PropertyChangeEvent[] events) {
    return ConfigSupport.sortAndDispatch(events, new Changed() {

        @Override
        public <T extends ConfigBeanProxy> NotProcessed changed(TYPE type, Class<T> tClass, T t) {
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "NetworkConfig changed {0} {1} {2}", new Object[] { type, tClass, t });
            }
            if (tClass == NetworkListener.class && t instanceof NetworkListener) {
                return processNetworkListener(type, (NetworkListener) t, events);
            } else if (tClass == Http.class && t instanceof Http) {
                return processProtocol(type, (Protocol) t.getParent(), events);
            } else if (tClass == FileCache.class && t instanceof FileCache) {
                return processProtocol(type, (Protocol) t.getParent().getParent(), null);
            } else if (tClass == Ssl.class && t instanceof Ssl) {
                /*
                         * Make sure the SSL parent is in fact a protocol.  It could
                         * be a jmx-connector.
                     */
                final ConfigBeanProxy parent = t.getParent();
                if (parent instanceof Protocol) {
                    return processProtocol(type, (Protocol) parent, null);
                }
            } else if (tClass == Protocol.class && t instanceof Protocol) {
                return processProtocol(type, (Protocol) t, null);
            } else if (tClass == ThreadPool.class && t instanceof ThreadPool) {
                NotProcessed notProcessed = null;
                ThreadPool threadPool = (ThreadPool) t;
                for (NetworkListener listener : threadPool.findNetworkListeners()) {
                    notProcessed = processNetworkListener(type, listener, null);
                }
                // Throw an unprocessed event change if one hasn't already if HTTP or ThreadPool monitoring is enabled.
                MonitoringService ms = config.getMonitoringService();
                String threadPoolLevel = ms.getModuleMonitoringLevels().getThreadPool();
                String httpServiceLevel = ms.getModuleMonitoringLevels().getHttpService();
                if (((threadPoolLevel != null && !threadPoolLevel.equals(OFF)) || (httpServiceLevel != null && !httpServiceLevel.equals(OFF))) && notProcessed == null) {
                    notProcessed = new NotProcessed("Monitoring statistics will be incorrect for " + threadPool.getName() + " until restart due to changed attribute(s).");
                }
                return notProcessed;
            } else if (tClass == Transport.class && t instanceof Transport) {
                NotProcessed notProcessed = null;
                for (NetworkListener listener : ((Transport) t).findNetworkListeners()) {
                    notProcessed = processNetworkListener(type, listener, null);
                }
                return notProcessed;
            } else if (tClass == VirtualServer.class && t instanceof VirtualServer && !grizzlyService.hasMapperUpdateListener()) {
                return processVirtualServer(type, (VirtualServer) t);
            } else if (tClass == SystemProperty.class && t instanceof SystemProperty) {
                NetworkConfig networkConfig = config.getNetworkConfig();
                if ((networkConfig != null) && ((SystemProperty) t).getName().endsWith("LISTENER_PORT")) {
                    for (NetworkListener listener : networkConfig.getNetworkListeners().getNetworkListener()) {
                        if (listener.getPort().equals(((SystemProperty) t).getValue())) {
                            return processNetworkListener(Changed.TYPE.CHANGE, listener, events);
                        }
                    }
                }
                return null;
            }
            return null;
        }
    }, logger);
}
Also used : ThreadPool(org.glassfish.grizzly.config.dom.ThreadPool) NetworkConfig(org.glassfish.grizzly.config.dom.NetworkConfig) Http(org.glassfish.grizzly.config.dom.Http) Ssl(org.glassfish.grizzly.config.dom.Ssl) SystemProperty(com.sun.enterprise.config.serverbeans.SystemProperty) VirtualServer(com.sun.enterprise.config.serverbeans.VirtualServer) FileCache(org.glassfish.grizzly.config.dom.FileCache) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) Changed(org.jvnet.hk2.config.Changed) NotProcessed(org.jvnet.hk2.config.NotProcessed) Protocol(org.glassfish.grizzly.config.dom.Protocol) Transport(org.glassfish.grizzly.config.dom.Transport) MonitoringService(com.sun.enterprise.config.serverbeans.MonitoringService) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener)

Aggregations

TransactionFailure (org.jvnet.hk2.config.TransactionFailure)15 Property (org.jvnet.hk2.config.types.Property)15 IOException (java.io.IOException)13 ActionReport (org.glassfish.api.ActionReport)13 PropertyVetoException (java.beans.PropertyVetoException)12 List (java.util.List)10 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)10 Method (java.lang.reflect.Method)9 HashMap (java.util.HashMap)9 Map (java.util.Map)7 Logger (java.util.logging.Logger)7 Service (org.jvnet.hk2.annotations.Service)7 ArrayList (java.util.ArrayList)6 Inject (javax.inject.Inject)6 MultiException (org.glassfish.hk2.api.MultiException)6 ConfigBean (org.jvnet.hk2.config.ConfigBean)6 NetworkListener (org.glassfish.grizzly.config.dom.NetworkListener)5 SystemProperty (com.sun.enterprise.config.serverbeans.SystemProperty)4 Collection (java.util.Collection)4 DeploymentException (org.glassfish.deployment.common.DeploymentException)4