Search in sources :

Example 16 with DeploymentContext

use of org.glassfish.api.deployment.DeploymentContext in project Payara by payara.

the class DisableCommand method execute.

/**
 * Entry point from the framework into the command execution
 * @param context context for the command.
 */
public void execute(AdminCommandContext context) {
    if (origin == Origin.unload && command == Command.disable) {
        // we should only validate this for the disable command
        deployment.validateSpecifiedTarget(target);
    }
    InterceptorNotifier notifier = new InterceptorNotifier(habitat, null);
    final DeployCommandSupplementalInfo suppInfo = new DeployCommandSupplementalInfo();
    suppInfo.setAccessChecks(accessChecks);
    report.setResultType(DeployCommandSupplementalInfo.class, suppInfo);
    if (env.isDas() && DeploymentUtils.isDomainTarget(target)) {
        // for each distinct enabled version in all known targets
        Iterator it = enabledVersionsInTargets.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            appName = (String) entry.getKey();
            List<String> targets = new ArrayList<String>((Set<String>) entry.getValue());
            // replicate command to all referenced targets
            try {
                ParameterMapExtractor extractor = new ParameterMapExtractor(this);
                ParameterMap paramMap = extractor.extract(Collections.EMPTY_LIST);
                paramMap.set("DEFAULT", appName);
                notifier.ensureBeforeReported(ExtendedDeploymentContext.Phase.REPLICATION);
                ClusterOperationUtil.replicateCommand("disable", FailurePolicy.Error, FailurePolicy.Warn, FailurePolicy.Ignore, targets, context, paramMap, habitat);
            } catch (Exception e) {
                report.failure(logger, e.getMessage());
                return;
            }
        }
    } else if (isVersionExpressionWithWildcard) {
        try {
            if (matchedVersions == Collections.EMPTY_LIST) {
                // no version matched by the expression
                // nothing to do : success
                report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
                return;
            }
            String enabledVersion = versioningService.getEnabledVersion(appName, target);
            if (matchedVersions.contains(enabledVersion)) {
                // the enabled version is matched by the expression
                appName = enabledVersion;
            } else {
                // the enabled version is not matched by the expression
                // nothing to do : success
                report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
                return;
            }
        } catch (VersioningException e) {
            report.failure(logger, e.getMessage());
            return;
        }
    }
    if (target == null) {
        target = deployment.getDefaultTarget(appName, origin, _classicstyle);
    }
    if (env.isDas() || !isundeploy) {
        // on instance side for partial deployment case
        if (!deployment.isRegistered(appName)) {
            if (env.isDas()) {
                // let's only do this check for DAS to be more
                // tolerable of the partial deployment case
                report.setMessage(localStrings.getLocalString("application.notreg", "Application {0} not registered", appName));
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            }
            return;
        }
        if (!DeploymentUtils.isDomainTarget(target)) {
            ApplicationRef ref = domain.getApplicationRefInTarget(appName, target);
            if (ref == null) {
                if (env.isDas()) {
                    // let's only do this check for DAS to be more
                    // tolerable of the partial deployment case
                    report.setMessage(localStrings.getLocalString("ref.not.referenced.target", "Application {0} is not referenced by target {1}", appName, target));
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                }
                return;
            }
        }
    }
    /*
         * If the target is a cluster instance, the DAS will broadcast the command
         * to all instances in the cluster so they can all update their configs.
         */
    if (env.isDas()) {
        try {
            notifier.ensureBeforeReported(ExtendedDeploymentContext.Phase.REPLICATION);
            DeploymentCommandUtils.replicateEnableDisableToContainingCluster("disable", domain, target, appName, habitat, context, this);
        } catch (Exception e) {
            report.failure(logger, e.getMessage());
            return;
        }
    }
    try {
        Application app = applications.getApplication(appName);
        this.name = appName;
        // SHOULD CHECK THAT WE ARE THE CORRECT TARGET BEFORE DISABLING
        String serverName = server.getName();
        if (serverName.equals(target) || (server.getCluster() != null && server.getCluster().getName().equals(target))) {
            // wait until all applications are loaded. Otherwise we get "Application not registered"
            startupProvider.get();
            ApplicationInfo appInfo = deployment.get(appName);
            final DeploymentContext basicDC = deployment.disable(this, app, appInfo, report, logger);
            suppInfo.setDeploymentContext((ExtendedDeploymentContext) basicDC);
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error during disabling: ", e);
        if (env.isDas() || !isundeploy) {
            // we should let undeployment go through
            // on instance side for partial deployment case
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setMessage(e.getMessage());
        }
    }
    if (enabledVersionsToDisable == Collections.EMPTY_SET) {
        enabledVersionsToDisable = new HashSet<String>();
        enabledVersionsToDisable.add(appName);
    }
    // iterating all the distinct enabled versions in all targets
    Iterator it = enabledVersionsToDisable.iterator();
    while (it.hasNext()) {
        appName = (String) it.next();
        if (!isundeploy && !report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            try {
                deployment.updateAppEnabledAttributeInDomainXML(appName, target, false);
            } catch (TransactionFailure e) {
                logger.warning("failed to set enable attribute for " + appName);
            }
        }
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) ArrayList(java.util.ArrayList) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ParameterMap(org.glassfish.api.admin.ParameterMap) VersioningException(org.glassfish.deployment.versioning.VersioningException) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) ParameterMapExtractor(org.glassfish.common.util.admin.ParameterMapExtractor) Iterator(java.util.Iterator) VersioningException(org.glassfish.deployment.versioning.VersioningException) Map(java.util.Map) ParameterMap(org.glassfish.api.admin.ParameterMap) HashMap(java.util.HashMap)

Example 17 with DeploymentContext

use of org.glassfish.api.deployment.DeploymentContext in project Payara by payara.

the class EnableCommand method execute.

/**
 * Entry point from the framework into the command execution
 * @param context context for the command.
 */
public void execute(AdminCommandContext context) {
    deployment.validateSpecifiedTarget(target);
    InterceptorNotifier notifier = new InterceptorNotifier(habitat, null);
    DeployCommandSupplementalInfo suppInfo = new DeployCommandSupplementalInfo();
    suppInfo.setDeploymentContext(notifier.dc());
    suppInfo.setAccessChecks(accessChecks);
    report.setResultType(DeployCommandSupplementalInfo.class, suppInfo);
    if (!deployment.isRegistered(name())) {
        report.setMessage(localStrings.getLocalString("application.notreg", "Application {0} not registered", name()));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    if (!DeploymentUtils.isDomainTarget(target)) {
        ApplicationRef applicationRef = domain.getApplicationRefInTarget(name(), target);
        if (applicationRef == null) {
            report.setMessage(localStrings.getLocalString("ref.not.referenced.target", "Application {0} is not referenced by target {1}", name(), target));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    // return if the application is already in enabled state
    if (domain.isAppEnabledInTarget(name(), target)) {
        logger.fine("The application is already enabled");
        return;
    }
    if (env.isDas()) {
        // try to disable the enabled version, if exist
        try {
            versioningService.handleDisable(name(), target, report, context.getSubject());
        } catch (VersioningSyntaxException e) {
            report.failure(logger, e.getMessage());
            return;
        }
        if (DeploymentUtils.isDomainTarget(target)) {
            List<String> targets = domain.getAllReferencedTargetsForApplication(name());
            // replicate command to all referenced targets
            try {
                ParameterMapExtractor extractor = new ParameterMapExtractor(this);
                ParameterMap paramMap = extractor.extract(Collections.EMPTY_LIST);
                paramMap.set("DEFAULT", name());
                notifier.ensureBeforeReported(Phase.REPLICATION);
                ClusterOperationUtil.replicateCommand("enable", FailurePolicy.Error, FailurePolicy.Warn, FailurePolicy.Ignore, targets, context, paramMap, habitat);
            } catch (Exception e) {
                report.failure(logger, e.getMessage());
                return;
            }
        }
        try {
            notifier.ensureBeforeReported(Phase.REPLICATION);
            DeploymentCommandUtils.replicateEnableDisableToContainingCluster("enable", domain, target, name(), habitat, context, this);
        } catch (Exception e) {
            report.failure(logger, e.getMessage());
            return;
        }
    }
    try {
        Application app = applications.getApplication(name());
        ApplicationRef appRef = domain.getApplicationRefInServer(server.getName(), name());
        // application is enabled.
        try {
            deployment.updateAppEnabledAttributeInDomainXML(name(), target, true);
        } catch (TransactionFailure e) {
            logger.log(Level.WARNING, "failed to set enable attribute for " + name(), e);
        }
        DeploymentContext dc = deployment.enable(target, app, appRef, report, logger);
        suppInfo.setDeploymentContext((ExtendedDeploymentContext) dc);
        if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            // update the domain.xml
            try {
                deployment.updateAppEnabledAttributeInDomainXML(name(), target, false);
            } catch (TransactionFailure e) {
                logger.log(Level.WARNING, "failed to set enable attribute for " + name(), e);
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error during enabling: ", e);
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(e.getMessage());
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) ParameterMapExtractor(org.glassfish.common.util.admin.ParameterMapExtractor) ParameterMap(org.glassfish.api.admin.ParameterMap) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException)

Example 18 with DeploymentContext

use of org.glassfish.api.deployment.DeploymentContext in project Payara by payara.

the class RarHandler method getClassLoader.

/**
 * {@inheritDoc}
 */
public ClassLoader getClassLoader(ClassLoader parent, DeploymentContext context) {
    try {
        String moduleDir = context.getSource().getURI().getPath();
        String moduleName = context.getSource().getName();
        List<URI> appLibs = null;
        try {
            appLibs = context.getAppLibs();
            if (_logger.isLoggable(Level.FINEST)) {
                _logger.log(Level.FINEST, "installed libraries (--applibs and EXTENSTION_LIST) for rar " + "[ " + moduleName + " ] :  " + appLibs);
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        ClassLoader carCL;
        if (isEmbedded(context)) {
            String applicationName = ConnectorsUtil.getApplicationName(context);
            String embeddedRarName = ConnectorsUtil.getEmbeddedRarModuleName(applicationName, moduleName);
            // ear's classloader hierarchy is : module-CL -> ear-CL (contains all ejb module classpath)
            // -> embedded-RAR-CL -> ear-lib-CL.
            // parent provided here is ear-CL, we need to use
            // ear-lib-CL as parent for embedded-RAR module-CL
            carCL = loader.createRARClassLoader(moduleDir, parent.getParent().getParent(), embeddedRarName, appLibs);
        } else {
            carCL = loader.createRARClassLoader(moduleDir, null, moduleName, appLibs);
        }
        try {
            final DeploymentContext dc = context;
            final ClassLoader cl = carCL;
            AccessController.doPrivileged(new PermsArchiveDelegate.SetPermissionsAction(SMGlobalPolicyUtil.CommponentType.rar, dc, cl));
        } catch (PrivilegedActionException e) {
            throw new SecurityException(e.getException());
        }
        return carCL;
    } catch (ConnectorRuntimeException e) {
        throw new RuntimeException(e);
    }
}
Also used : PermsArchiveDelegate(com.sun.enterprise.security.perms.PermsArchiveDelegate) ConnectorRuntimeException(com.sun.appserv.connectors.internal.api.ConnectorRuntimeException) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ConnectorRuntimeException(com.sun.appserv.connectors.internal.api.ConnectorRuntimeException) PrivilegedActionException(java.security.PrivilegedActionException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 19 with DeploymentContext

use of org.glassfish.api.deployment.DeploymentContext in project Payara by payara.

the class JPADeployer method iterateInitializedPUsAtApplicationPrepare.

/**
 * Does java2db on DAS and saves emfs created during prepare to ApplicationInfo maintained by DOL.
 * ApplicationInfo is not available during prepare() so we can not directly use it there.
 * @param context
 */
private void iterateInitializedPUsAtApplicationPrepare(final DeploymentContext context) {
    final DeployCommandParameters deployCommandParameters = context.getCommandParameters(DeployCommandParameters.class);
    String appName = deployCommandParameters.name;
    final ApplicationInfo appInfo = applicationRegistry.get(appName);
    // iterate through all the PersistenceUnitDescriptor for this bundle.
    PersistenceUnitDescriptorIterator pudIterator = new PersistenceUnitDescriptorIterator() {

        @Override
        void visitPUD(PersistenceUnitDescriptor pud, DeploymentContext context) {
            // PersistenceUnitsDescriptor corresponds to  persistence.xml. A bundle can only have one persitence.xml except
            // when the bundle is an application which can have multiple persitence.xml under jars in root of ear and lib.
            PersistenceUnitLoader puLoader = context.getTransientAppMetaData(getUniquePuIdentifier(pud), PersistenceUnitLoader.class);
            if (puLoader != null) {
                // We have initialized PU
                boolean saveEMF = true;
                if (isDas()) {
                    // We do validation and execute Java2DB only on DAS
                    if (deployCommandParameters.origin.isDeploy()) {
                        // APPLICATION_PREPARED will be called for create-application-ref also. We should perform java2db only on first deploy
                        // Create EM to trigger validation on PU
                        EntityManagerFactory emf = puLoader.getEMF();
                        EntityManager em = null;
                        try {
                            // Create EM to trigger any validations that are lazily performed by the provider
                            // EM creation also triggers DDL generation by provider.
                            em = emf.createEntityManager();
                        } catch (PersistenceException e) {
                            // Exception indicates something went wrong while performing validation. Clean up and rethrow to fail deployment
                            emf.close();
                            DeployCommandParameters dcp = context.getCommandParameters(DeployCommandParameters.class);
                            if (dcp.isSkipDSFailure() && ExceptionUtil.isDSFailure(e)) {
                                logger.log(Level.WARNING, "Resource communication failure exception skipped while loading the pu " + pud.getName(), e);
                            } else {
                                // Need to wrap exception in DeploymentException else deployment will not fail !!
                                throw new DeploymentException(e);
                            }
                        } finally {
                            if (em != null) {
                                em.close();
                            }
                        }
                        puLoader.doJava2DB();
                        boolean enabled = deployCommandParameters.enabled;
                        boolean isTargetDas = isTargetDas(deployCommandParameters);
                        if (logger.isLoggable(Level.FINER)) {
                            logger.finer("iterateInitializedPUsAtApplicationPrepare(): enabled: " + enabled + " isTargetDas: " + isTargetDas);
                        }
                        if (!isTargetDas || !enabled) {
                            // we are on DAS but target != das or app is not enabled on das => The EMF was just created for Java2Db. Close it.
                            puLoader.getEMF().close();
                            // Do not save EMF. We have already closed it
                            saveEMF = false;
                        }
                    }
                }
                if (saveEMF) {
                    // Save emf in ApplicationInfo so that it can be retrieved and closed for cleanup
                    // Suppress warning required as there is no way to pass equivalent of List<EMF>.class to the method
                    @SuppressWarnings("unchecked") List<EntityManagerFactory> emfsCreatedForThisApp = appInfo.getTransientAppMetaData(EMF_KEY, List.class);
                    if (emfsCreatedForThisApp == null) {
                        // First EMF for this app, initialize
                        emfsCreatedForThisApp = new ArrayList<EntityManagerFactory>();
                        appInfo.addTransientAppMetaData(EMF_KEY, emfsCreatedForThisApp);
                    }
                    emfsCreatedForThisApp.add(puLoader.getEMF());
                }
            // if (saveEMF)
            }
        // if(puLoader != null)
        }
    };
    pudIterator.iteratePUDs(context);
}
Also used : ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) EntityManager(javax.persistence.EntityManager) EntityManagerFactory(javax.persistence.EntityManagerFactory) PersistenceException(javax.persistence.PersistenceException) DeploymentException(org.glassfish.deployment.common.DeploymentException)

Example 20 with DeploymentContext

use of org.glassfish.api.deployment.DeploymentContext in project Payara by payara.

the class WarHandler method getClassLoader.

@Override
public ClassLoader getClassLoader(final ClassLoader parent, final DeploymentContext context) {
    Application applicationTemp = context.getModuleMetaData(Application.class);
    final Application application = applicationTemp == null ? Application.createApplication() : applicationTemp;
    WebappClassLoader cloader = AccessController.doPrivileged(new PrivilegedAction<WebappClassLoader>() {

        @Override
        public WebappClassLoader run() {
            return new WebappClassLoader(parent, application);
        }
    });
    try {
        WebDirContext r = new WebDirContext();
        File base = new File(context.getSource().getURI());
        r.setDocBase(base.getAbsolutePath());
        cloader.setResources(r);
        cloader.addRepository("WEB-INF/classes/", new File(base, "WEB-INF/classes/"));
        if (context.getScratchDir("ejb") != null) {
            cloader.addRepository(context.getScratchDir("ejb").toURI().toURL().toString().concat("/"));
        }
        if (context.getScratchDir("jsp") != null) {
            cloader.setWorkDir(context.getScratchDir("jsp"));
        }
        // add libraries referenced from manifest
        for (URL url : getManifestLibraries(context)) {
            cloader.addRepository(url.toString());
        }
        WebXmlParser webXmlParser = getWebXmlParser(context.getSource(), application);
        configureLoaderAttributes(cloader, webXmlParser, base);
        configureLoaderProperties(cloader, webXmlParser, base);
        configureContextXmlAttribute(cloader, base, context);
        try {
            final DeploymentContext dc = context;
            final ClassLoader cl = cloader;
            AccessController.doPrivileged(new PermsArchiveDelegate.SetPermissionsAction(SMGlobalPolicyUtil.CommponentType.war, dc, cl));
        } catch (PrivilegedActionException e) {
            throw new SecurityException(e.getException());
        }
    } catch (XMLStreamException xse) {
        logger.log(Level.SEVERE, xse.getMessage());
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, xse.getMessage(), xse);
        }
        xse.printStackTrace();
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, ioe.getMessage());
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, ioe.getMessage(), ioe);
        }
        ioe.printStackTrace();
    }
    cloader.start();
    return cloader;
}
Also used : PermsArchiveDelegate(com.sun.enterprise.security.perms.PermsArchiveDelegate) WebDirContext(org.apache.naming.resources.WebDirContext) PrivilegedActionException(java.security.PrivilegedActionException) URL(java.net.URL) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) XMLStreamException(javax.xml.stream.XMLStreamException) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) Application(com.sun.enterprise.deployment.Application) JarFile(java.util.jar.JarFile)

Aggregations

DeploymentContext (org.glassfish.api.deployment.DeploymentContext)27 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)11 DeployCommandParameters (org.glassfish.api.deployment.DeployCommandParameters)10 ApplicationInfo (org.glassfish.internal.data.ApplicationInfo)6 URL (java.net.URL)5 ParameterMap (org.glassfish.api.admin.ParameterMap)5 PermsArchiveDelegate (com.sun.enterprise.security.perms.PermsArchiveDelegate)4 URI (java.net.URI)4 PrivilegedActionException (java.security.PrivilegedActionException)4 Container (com.sun.ejb.Container)3 AbstractSingletonContainer (com.sun.ejb.containers.AbstractSingletonContainer)3 Application (com.sun.enterprise.deployment.Application)3 ArrayList (java.util.ArrayList)3 Properties (java.util.Properties)3 ActionReport (org.glassfish.api.ActionReport)3 ApplicationContainer (org.glassfish.api.deployment.ApplicationContainer)3 ReadableArchive (org.glassfish.api.deployment.archive.ReadableArchive)3 ParameterMapExtractor (org.glassfish.common.util.admin.ParameterMapExtractor)3 DeploymentProperties (org.glassfish.deployment.common.DeploymentProperties)3 VersioningException (org.glassfish.deployment.versioning.VersioningException)3