Search in sources :

Example 16 with Transaction

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

the class CreateLifecycleModuleCommand method execute.

public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    try {
        validateTarget(target, name);
    } catch (IllegalArgumentException ie) {
        report.setMessage(ie.getMessage());
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    DeployCommandParameters commandParams = new DeployCommandParameters();
    commandParams.name = name;
    commandParams.enabled = enabled;
    commandParams.description = description;
    commandParams.target = target;
    // create a dummy context to hold params and props
    ExtendedDeploymentContext deploymentContext = new DeploymentContextImpl(report, null, commandParams, null);
    Properties appProps = deploymentContext.getAppProps();
    if (property != null) {
        appProps.putAll(property);
    }
    // set to default "user", deployers can override it
    appProps.setProperty(ServerTags.OBJECT_TYPE, "user");
    appProps.setProperty(ServerTags.CLASS_NAME, classname);
    if (classpath != null) {
        appProps.setProperty(ServerTags.CLASSPATH, classpath);
    }
    if (loadorder != null) {
        appProps.setProperty(ServerTags.LOAD_ORDER, loadorder);
    }
    appProps.setProperty(ServerTags.IS_FAILURE_FATAL, failurefatal.toString());
    appProps.setProperty(ServerTags.IS_LIFECYCLE, "true");
    try {
        Transaction t = deployment.prepareAppConfigChanges(deploymentContext);
        deployment.registerAppInDomainXML(null, deploymentContext, t);
    } catch (Exception e) {
        report.setMessage("Failed to create lifecycle module: " + e);
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
}
Also used : DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) Transaction(org.jvnet.hk2.config.Transaction) ActionReport(org.glassfish.api.ActionReport) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Properties(java.util.Properties) DeploymentContextImpl(org.glassfish.deployment.common.DeploymentContextImpl)

Example 17 with Transaction

use of org.jvnet.hk2.config.Transaction 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;
    try {
        // 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);
        if (tracing != null) {
            tracing.addMark(DeploymentTracing.Mark.TARGET_VALIDATED);
        }
        ActionReport.MessagePart part = report.getTopMessagePart();
        part.addProperty(DeploymentProperties.NAME, name);
        ApplicationConfigInfo savedAppConfig = new ApplicationConfigInfo(apps.getModule(Application.class, name));
        Properties undeployProps = handleRedeploy(name, report, context);
        if (enabled == null) {
            enabled = Boolean.TRUE;
        }
        // clean up any left over repository files
        if (!keepreposdir.booleanValue()) {
            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();
            }
        }
        if (!DeploymentUtils.isDomainTarget(target) && enabled) {
            // 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;
            }
        }
        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;
            }
        }
        // create the parent class loader
        deploymentContext = deployment.getBuilder(logger, this, report).source(initialContext.getSource()).archiveHandler(archiveHandler).build(initialContext);
        if (tracing != null) {
            tracing.addMark(DeploymentTracing.Mark.CONTEXT_CREATED);
            deploymentContext.addModuleMetaData(tracing);
        }
        // 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);
        }
        // clean up any generated files
        deploymentContext.clean();
        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 t = deployment.prepareAppConfigChanges(deploymentContext);
        if (tracing != null) {
            tracing.addMark(DeploymentTracing.Mark.DEPLOY);
        }
        Deployment.ApplicationDeployment deplResult = deployment.prepare(null, deploymentContext);
        if (!loadOnly) {
            deployment.initialize(deplResult.appInfo, deplResult.appInfo.getSniffers(), deplResult.context);
        }
        ApplicationInfo appInfo = deplResult.appInfo;
        /*
             * 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 {
                moveAppFilesToPermanentLocation(deploymentContext, logger);
                recordFileLocations(appProps);
                downloadableArtifacts.record(appProps);
                generatedArtifacts.record(appProps);
                // Set the application deploy time
                timeTakenToDeploy = timing.elapsed();
                deploymentContext.getTransientAppMetaData("application", Application.class).setDeploymentTime(Long.toString(timeTakenToDeploy));
                deploymentTimeMillis = System.currentTimeMillis();
                deploymentContext.getTransientAppMetaData("application", Application.class).setTimeDeployed(Long.toString(deploymentTimeMillis));
                // register application information in domain.xml
                deployment.registerAppInDomainXML(appInfo, deploymentContext, t);
                if (tracing != null) {
                    tracing.addMark(DeploymentTracing.Mark.REGISTRATION);
                }
                if (retrieve != null) {
                    retrieveArtifacts(context, downloadableArtifacts.getArtifacts(), retrieve, false, name);
                }
                suppInfo.setDeploymentContext(deploymentContext);
                // 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);
        if (e.getMessage() != null) {
            report.setMessage(e.getMessage());
            report.setFailureCause(e);
        } else {
            report.setFailureCause(null);
        }
    } 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 (tracing != null) {
            tracing.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);
                }
            }
        }
        if (deploymentContext != null && !loadOnly) {
            deploymentContext.postDeployClean(true);
        }
    }
}
Also used : ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ActionReport(org.glassfish.api.ActionReport) URI(java.net.URI) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) ExitCode(org.glassfish.api.ActionReport.ExitCode) IOException(java.io.IOException) RestEndpoint(org.glassfish.api.admin.RestEndpoint) URISyntaxException(java.net.URISyntaxException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) IOException(java.io.IOException) Transaction(org.jvnet.hk2.config.Transaction) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) File(java.io.File)

Example 18 with Transaction

use of org.jvnet.hk2.config.Transaction 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);
        }
    }
}
Also used : ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) IOException(java.io.IOException) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) IOException(java.io.IOException) Transaction(org.jvnet.hk2.config.Transaction) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) ZipFile(java.util.zip.ZipFile) File(java.io.File) Application(com.sun.enterprise.config.serverbeans.Application)

Example 19 with Transaction

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

the class InstanceLifecycleModuleCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    final Logger logger = context.getLogger();
    try {
        Application application = applications.getApplication(name);
        Transaction t = new Transaction();
        // create a dummy context to hold params and props
        DeployCommandParameters commandParams = new DeployCommandParameters();
        commandParams.name = name;
        commandParams.target = target;
        commandParams.enabled = enabled;
        commandParams.virtualservers = virtualservers;
        ExtendedDeploymentContext lifecycleContext = new DeploymentContextImpl(report, null, commandParams, null);
        lifecycleContext.getAppProps().putAll(appprops);
        if (application != null) {
            // application element already been synchronized over
            // just write application-ref
            deployment.registerAppInDomainXML(null, lifecycleContext, t, true);
        } else {
            // write both
            t = deployment.prepareAppConfigChanges(lifecycleContext);
            deployment.registerAppInDomainXML(null, lifecycleContext, t);
        }
    } catch (Exception e) {
        report.failure(logger, e.getMessage());
    }
}
Also used : DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) Transaction(org.jvnet.hk2.config.Transaction) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Application(com.sun.enterprise.config.serverbeans.Application) DeploymentContextImpl(org.glassfish.deployment.common.DeploymentContextImpl)

Example 20 with Transaction

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

the class ExampleConfigUpdateOnlyOnDAS method execute.

@Override
public void execute(AdminCommandContext context) {
    // obtain the correct configuration
    Config configVal = targetUtil.getConfig(target);
    ExampleServiceConfiguration serviceConfig = configVal.getExtensionByType(ExampleServiceConfiguration.class);
    if (serviceConfig != null) {
        try {
            // to perform a transaction on the domain.xml you need to use this construct
            // see https://github.com/hk2-project/hk2/blob/master/hk2-configuration/persistence/hk2-xml-dom/hk2-config/src/main/java/org/jvnet/hk2/config/ConfigSupport.java
            ConfigSupport.apply(new SingleConfigCode<ExampleServiceConfiguration>() {

                @Override
                public Object run(ExampleServiceConfiguration config) {
                    config.setMessage(message);
                    return null;
                }
            }, serviceConfig);
        } catch (TransactionFailure ex) {
            // set failure
            context.getActionReport().failure(Logger.getLogger(SetExampleServiceMessage.class.getName()), "Failed to update message", ex);
        }
    } else {
        context.getActionReport().failure(Logger.getLogger(this.getClass().getCanonicalName()), "No configuration with name " + target);
    }
}
Also used : ExampleServiceConfiguration(fish.payara.service.example.config.ExampleServiceConfiguration) TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Config(com.sun.enterprise.config.serverbeans.Config)

Aggregations

TransactionFailure (org.jvnet.hk2.config.TransactionFailure)14 Transaction (org.jvnet.hk2.config.Transaction)13 PropertyVetoException (java.beans.PropertyVetoException)10 Property (org.jvnet.hk2.config.types.Property)9 IOException (java.io.IOException)6 ActionReport (org.glassfish.api.ActionReport)6 File (java.io.File)5 Properties (java.util.Properties)5 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)5 Config (com.sun.enterprise.config.serverbeans.Config)4 Domain (com.sun.enterprise.config.serverbeans.Domain)4 DeployCommandParameters (org.glassfish.api.deployment.DeployCommandParameters)4 VersioningSyntaxException (org.glassfish.deployment.versioning.VersioningSyntaxException)4 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)4 ArrayList (java.util.ArrayList)3 Iterator (java.util.Iterator)3 Application (com.sun.enterprise.config.serverbeans.Application)2 Resource (com.sun.enterprise.config.serverbeans.Resource)2 Server (com.sun.enterprise.config.serverbeans.Server)2 SystemProperty (com.sun.enterprise.config.serverbeans.SystemProperty)2