Search in sources :

Example 41 with FileArchive

use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.

the class JaxRpcRICodegen method run.

@Override
public void run(ServiceLocator habitat, DeploymentContext context, String cp) throws Exception {
    rootLocation_ = new FileArchive();
    BundleDescriptor bundle = DOLUtils.getCurrentBundleForContext(context);
    if (bundle.hasWebServiceClients() && (bundle instanceof ApplicationClientDescriptor)) {
        hasWebServiceClients = true;
    }
    if (bundle.isStandalone()) {
        rootLocation_.open(context.getSourceDir().toURI());
    } else {
        rootLocation_.open(context.getSource().getParentArchive().getURI());
    }
    this.context = context;
    this.habitat = habitat;
    this.moduleClassPath = cp;
    Application application = context.getModuleMetaData(Application.class);
    application.visit(this);
}
Also used : BundleDescriptor(com.sun.enterprise.deployment.BundleDescriptor) WebBundleDescriptor(com.sun.enterprise.deployment.WebBundleDescriptor) EjbBundleDescriptor(com.sun.enterprise.deployment.EjbBundleDescriptor) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) ApplicationClientDescriptor(com.sun.enterprise.deployment.ApplicationClientDescriptor) Application(com.sun.enterprise.deployment.Application)

Example 42 with FileArchive

use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.

the class DeployCommand method execute.

/**
 * Entry point from the framework into the command execution
 *
 * @param context context for the command.
 */
@Override
public void execute(AdminCommandContext context) {
    long timeTakenToDeploy = 0;
    long deploymentTimeMillis = 0;
    Optional<ApplicationState> appState = Optional.empty();
    final ActionReport report = context.getActionReport();
    try (SpanSequence span = structuredTracing.startSequence(DeploymentTracing.AppStage.VALIDATE_TARGET, "registry")) {
        if (!hotDeploy) {
            hotDeployService.removeApplicationState(initialContext.getSourceDir());
        } else if (!(appState = hotDeployService.getApplicationState(initialContext.getSourceDir())).isPresent()) {
            ApplicationState applicationState = new ApplicationState(name, path, initialContext);
            applicationState.setTarget(target);
            appState = Optional.of(applicationState);
        }
        // needs to be fixed in hk2, we don't generate the right innerclass index. it should use $
        Collection<Interceptor> interceptors = habitat.getAllServices(Interceptor.class);
        if (interceptors != null) {
            for (Interceptor interceptor : interceptors) {
                interceptor.intercept(this, initialContext);
            }
        }
        deployment.validateDeploymentTarget(target, name, isredeploy);
        ActionReport.MessagePart part = report.getTopMessagePart();
        part.addProperty(DeploymentProperties.NAME, name);
        ApplicationConfigInfo savedAppConfig = new ApplicationConfigInfo(apps.getModule(Application.class, name));
        Properties undeployProps = null;
        if (appState.map(ApplicationState::isInactive).orElse(true)) {
            undeployProps = handleRedeploy(name, report, context);
        }
        appState.filter(ApplicationState::isInactive).ifPresent(hotDeployService::addApplicationState);
        if (enabled == null) {
            enabled = Boolean.TRUE;
        }
        // clean up any left over repository files
        if (!keepreposdir) {
            span.start(DeploymentTracing.AppStage.CLEANUP, "applications");
            final File reposDir = new File(env.getApplicationRepositoryPath(), VersioningUtils.getRepositoryName(name));
            if (reposDir.exists()) {
                for (int i = 0; i < domain.getApplications().getApplications().size(); i++) {
                    File existrepos = new File(new URI(domain.getApplications().getApplications().get(i).getLocation()));
                    String appname = domain.getApplications().getApplications().get(i).getName();
                    if (!appname.equals(name) && existrepos.getAbsoluteFile().equals(reposDir.getAbsoluteFile())) {
                        report.failure(logger, localStrings.getLocalString("deploy.dupdeployment", "Application {0} is trying to use the same repository directory as application {1}, please choose a different application name to deploy", name, appname));
                        return;
                    }
                }
                /*
                     * Delete the repository directory as an archive to allow
                     * any special processing (such as stale file handling)
                     * to run.
                     */
                final FileArchive arch = DeploymentUtils.openAsFileArchive(reposDir, archiveFactory);
                arch.delete();
            }
            span.finish();
        }
        if (!DeploymentUtils.isDomainTarget(target) && enabled) {
            // try to disable the enabled version, if exist
            try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.SWITCH_VERSIONS)) {
                versioningService.handleDisable(name, target, report, context.getSubject());
            } catch (VersioningSyntaxException e) {
                report.failure(logger, e.getMessage());
                return;
            }
        }
        File source = new File(archive.getURI().getSchemeSpecificPart());
        boolean isDirectoryDeployed = true;
        if (!source.isDirectory()) {
            isDirectoryDeployed = false;
            expansionDir = new File(domain.getApplicationRoot(), VersioningUtils.getRepositoryName(name));
            path = expansionDir;
        } else {
            // test if a version is already directory deployed from this dir
            String versionFromSameDir = versioningService.getVersionFromSameDir(source);
            if (!force && versionFromSameDir != null) {
                report.failure(logger, VersioningUtils.LOCALSTRINGS.getLocalString("versioning.deployment.dual.inplace", "GlassFish do not support versioning for directory deployment when using the same directory. The directory {0} is already assigned to the version {1}.", source.getPath(), versionFromSameDir));
                return;
            }
        }
        span.start(DeploymentTracing.AppStage.CREATE_DEPLOYMENT_CONTEXT, "Full");
        // create the parent class loader
        deploymentContext = deployment.getBuilder(logger, this, report).source(initialContext.getSource()).archiveHandler(archiveHandler).build(initialContext);
        String transformNS = System.getProperty(TRANSFORM_NAMESPACE);
        Types types = deployment.getDeployableTypes(deploymentContext);
        if (Boolean.valueOf(transformNS) || (transformNS == null && PayaraTransformer.isJakartaEEApplication(types))) {
            span.start(DeploymentTracing.AppStage.TRANSFORM_ARCHIVE);
            deploymentContext.getSource().close();
            File output = PayaraTransformer.transformApplication(path, context, isDirectoryDeployed);
            if (output == null) {
                return;
            }
            deploymentContext.setSource((FileArchive) archiveFactory.createArchive(output));
            // reset transient and module data of orignal deployed archive
            deploymentContext.removeTransientAppMetaData(Types.class.getName());
            deploymentContext.removeTransientAppMetaData(Parser.class.getName());
            deploymentContext.resetModuleMetaData();
            structuredTracing.register(deploymentContext);
        }
        // reset the properties (might be null) set by the deployers when undeploying.
        if (undeployProps != null) {
            deploymentContext.getAppProps().putAll(undeployProps);
        }
        if (properties != null || property != null) {
            // check for both
            if (properties == null) {
                properties = new Properties();
            }
            if (property != null) {
                properties.putAll(property);
            }
        }
        if (properties != null) {
            deploymentContext.getAppProps().putAll(properties);
            validateDeploymentProperties(properties, deploymentContext);
        }
        span.start(DeploymentTracing.AppStage.CLEANUP, "generated");
        // clean up any generated files
        deploymentContext.clean();
        span.start(DeploymentTracing.AppStage.PREPARE, "ServerConfig");
        Properties appProps = deploymentContext.getAppProps();
        /*
             * If the app's location is within the domain's directory then
             * express it in the config as ${com.sun.aas.instanceRootURI}/rest-of-path
             * so users can relocate the entire installation without having
             * to modify the app locations.  Leave the location alone if
             * it does not fall within the domain directory.
             */
        String appLocation = DeploymentUtils.relativizeWithinDomainIfPossible(deploymentContext.getSource().getURI());
        appProps.setProperty(ServerTags.LOCATION, appLocation);
        // set to default "user", deployers can override it
        // during processing
        appProps.setProperty(ServerTags.OBJECT_TYPE, "user");
        if (contextroot != null) {
            appProps.setProperty(ServerTags.CONTEXT_ROOT, contextroot);
        }
        appProps.setProperty(ServerTags.DIRECTORY_DEPLOYED, String.valueOf(isDirectoryDeployed));
        if (type == null) {
            type = archiveHandler.getArchiveType();
        }
        appProps.setProperty(Application.ARCHIVE_TYPE_PROP_NAME, type);
        if (appProps.getProperty(ServerTags.CDI_DEV_MODE_ENABLED_PROP) == null) {
            appProps.setProperty(ServerTags.CDI_DEV_MODE_ENABLED_PROP, Boolean.FALSE.toString());
        }
        savedAppConfig.store(appProps);
        deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_TARGETS, previousTargets);
        deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_VIRTUAL_SERVERS, previousVirtualServers);
        deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_ENABLED_ATTRIBUTES, previousEnabledAttributes);
        Transaction tx = deployment.prepareAppConfigChanges(deploymentContext);
        // next phase is launched by prepare
        span.finish();
        Deployment.ApplicationDeployment deplResult = deployment.prepare(null, deploymentContext);
        if (deplResult != null && !loadOnly) {
            appState.ifPresent(s -> s.storeMetaData(deploymentContext));
            // initialize makes its own phase as well
            deployment.initialize(deplResult.appInfo, deplResult.appInfo.getSniffers(), deplResult.context);
        }
        ApplicationInfo appInfo = deplResult != null ? deplResult.appInfo : null;
        /*
             * Various deployers might have added to the downloadable or
             * generated artifacts.  Extract them and, if the command succeeded,
             * persist both into the app properties (which will be recorded
             * in domain.xml).
             */
        final Artifacts downloadableArtifacts = DeploymentUtils.downloadableArtifacts(deploymentContext);
        final Artifacts generatedArtifacts = DeploymentUtils.generatedArtifacts(deploymentContext);
        if (report.getActionExitCode() == ActionReport.ExitCode.SUCCESS) {
            try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.REGISTRATION)) {
                moveAppFilesToPermanentLocation(deploymentContext, logger);
                recordFileLocations(appProps);
                downloadableArtifacts.record(appProps);
                generatedArtifacts.record(appProps);
                timeTakenToDeploy = timing.elapsed();
                deploymentTimeMillis = System.currentTimeMillis();
                if (tx != null) {
                    Application application = deploymentContext.getTransientAppMetaData("application", Application.class);
                    // Set the application deploy time
                    application.setDeploymentTime(Long.toString(timeTakenToDeploy));
                    application.setTimeDeployed(Long.toString(deploymentTimeMillis));
                    // register application information in domain.xml
                    deployment.registerAppInDomainXML(appInfo, deploymentContext, tx);
                }
                if (retrieve != null) {
                    retrieveArtifacts(context, downloadableArtifacts.getArtifacts(), retrieve, false, name);
                }
                suppInfo.setDeploymentContext(deploymentContext);
                // send new event to notify the deployment process is finish
                events.send(new Event<ApplicationInfo>(Deployment.DEPLOYMENT_COMMAND_FINISH, appInfo), false);
                // Fix for issue 14442
                // We want to report the worst subreport value.
                ActionReport.ExitCode worstExitCode = ExitCode.SUCCESS;
                for (ActionReport subReport : report.getSubActionsReport()) {
                    ActionReport.ExitCode actionExitCode = subReport.getActionExitCode();
                    if (actionExitCode.isWorse(worstExitCode)) {
                        worstExitCode = actionExitCode;
                    }
                }
                report.setActionExitCode(worstExitCode);
                report.setResultType(String.class, name);
            } catch (Exception e) {
                // roll back the deployment and re-throw the exception
                deployment.undeploy(name, deploymentContext);
                deploymentContext.clean();
                throw e;
            }
        }
    } catch (Throwable e) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setFailureCause(e);
        if (e.getMessage() != null) {
            report.setMessage(e.getMessage());
        }
    } finally {
        events.unregister(this);
        try {
            archive.close();
        } catch (IOException e) {
            logger.log(Level.FINE, localStrings.getLocalString("errClosingArtifact", "Error while closing deployable artifact : ", path.getAbsolutePath()), e);
        }
        if (structuredTracing.isEnabled()) {
            structuredTracing.print(System.out);
        }
        if (report.getActionExitCode().equals(ActionReport.ExitCode.SUCCESS)) {
            // Set the app name in the result so that embedded deployer can retrieve it.
            report.setResultType(String.class, name);
            report.setMessage(localStrings.getLocalString("deploy.command.success", "Application deployed with name {0}", name));
            logger.info(localStrings.getLocalString("deploy.done", "Deployment of {0} done is {1} ms at {2}", name, timeTakenToDeploy, DateFormat.getDateInstance().format(new Date(deploymentTimeMillis))));
        } else if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            String errorMessage = report.getMessage();
            Throwable cause = report.getFailureCause();
            if (cause != null) {
                String causeMessage = cause.getMessage();
                if (causeMessage != null && !causeMessage.equals(errorMessage)) {
                    errorMessage = errorMessage + " : " + cause.getMessage();
                }
                logger.log(Level.SEVERE, errorMessage, cause.getCause());
            }
            report.setMessage(localStrings.getLocalString("deploy.errDuringDepl", "Error occur during deployment: {0}.", errorMessage));
            // reset the failure cause so command framework will not try
            // to print the same message again
            report.setFailureCause(null);
            if (expansionDir != null) {
                final FileArchive arch;
                try {
                    /*
                         * Open and then delete the expansion directory as
                         * a file archive so stale file handling can run.
                         */
                    arch = DeploymentUtils.openAsFileArchive(expansionDir, archiveFactory);
                    arch.delete();
                } catch (IOException ex) {
                    final String msg = localStrings.getLocalString("deploy.errDelRepos", "Error deleting repository directory {0}", expansionDir.getAbsolutePath());
                    report.failure(logger, msg, ex);
                }
            }
            appState.map(ApplicationState::getPath).ifPresent(hotDeployService::removeApplicationState);
        }
        if (deploymentContext != null && !loadOnly) {
            deploymentContext.postDeployClean(true);
        }
        appState.ifPresent(ApplicationState::close);
    }
}
Also used : EventTypes(org.glassfish.api.event.EventTypes) Types(org.glassfish.hk2.classmodel.reflect.Types) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ActionReport(org.glassfish.api.ActionReport) URI(java.net.URI) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) SpanSequence(org.glassfish.internal.deployment.analysis.SpanSequence) ApplicationState(fish.payara.nucleus.hotdeploy.ApplicationState) 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) Parser(org.glassfish.hk2.classmodel.reflect.Parser) Transaction(org.jvnet.hk2.config.Transaction) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) File(java.io.File)

Example 43 with FileArchive

use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.

the class ResourcesUtil method getConnectorDescriptorFromUri.

public ConnectorDescriptor getConnectorDescriptorFromUri(String rarName, String raLoc) {
    try {
        String appName = rarName.substring(0, rarName.indexOf(ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER));
        // String actualRarName = rarName.substring(rarName.indexOf(ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER) + 1);
        String appDeployLocation = ResourcesUtil.createInstance().getApplicationDeployLocation(appName);
        FileArchive in = ConnectorRuntime.getRuntime().getFileArchive();
        in.open(new URI(appDeployLocation));
        ApplicationArchivist archivist = ConnectorRuntime.getRuntime().getApplicationArchivist();
        com.sun.enterprise.deployment.Application application = archivist.open(in);
        return application.getModuleByTypeAndUri(ConnectorDescriptor.class, raLoc);
    } catch (Exception e) {
        Object[] params = new Object[] { rarName, e };
        _logger.log(Level.WARNING, "error.getting.connector.descriptor", params);
    }
    return null;
}
Also used : ApplicationArchivist(com.sun.enterprise.deployment.archivist.ApplicationArchivist) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) URI(java.net.URI) ConnectorRuntimeException(com.sun.appserv.connectors.internal.api.ConnectorRuntimeException)

Example 44 with FileArchive

use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.

the class ConnectorDDTransformUtils method getConnectorDescriptor.

/**
 * Get the ConnectorDescriptor object which represents the ra.xml and
 * sun-ra.xml from an exploded rar module.
 *
 * @param moduleDir Directory where rar is exploded.
 * @return ConnectorDescriptor object which
 *         represents the ra.xml and sun-ra.xml
 * @throws ConnectorRuntimeException if ra.xml could not be located or
 *                                   invalid. For 1.0 type rar if sun-ra.xml is not present or
 *                                   invalid this exception is thrown. For 1.5 type rar sun-ra.xml
 *                                   should not be  present.
 */
public static ConnectorDescriptor getConnectorDescriptor(String moduleDir, String rarModuleName) throws ConnectorRuntimeException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        File module = new File(moduleDir);
        FileArchive fileArchive = new FileArchive();
        // directory where rar is exploded
        fileArchive.open(module.toURI());
        ConnectorRuntime runtime = ConnectorRuntime.getRuntime();
        ClassLoader loader;
        if (ConnectorsUtil.belongsToSystemRA(rarModuleName)) {
            loader = ConnectorRuntime.getRuntime().getSystemRARClassLoader(rarModuleName);
            Thread.currentThread().setContextClassLoader(loader);
        } else {
            loader = runtime.createConnectorClassLoader(moduleDir, null, rarModuleName);
        }
        ConnectorArchivist connectorArchivist = runtime.getConnectorArchvist();
        // TODO V3 what happens to embedded .rar ? as its parent classloader should be application CL
        // setting the classloader so that annotation processor can make use of it.
        connectorArchivist.setClassLoader(loader);
        // fileArchive.entries("META-INF/ra.xml");
        // TODO V3 need to check whether ra.xml is present, if so, check the version. process annotations
        // only if its 1.6 or above ?
        connectorArchivist.setAnnotationProcessingRequested(true);
        return connectorArchivist.open(fileArchive);
    } catch (IOException ex) {
        ConnectorRuntimeException cre = new ConnectorRuntimeException("Failed to read the connector deployment descriptors");
        cre.initCause(ex);
        _logger.log(Level.SEVERE, "rardeployment.connector_descriptor_read_error", moduleDir);
        _logger.log(Level.SEVERE, "", cre);
        throw cre;
    } catch (SAXParseException ex) {
        ConnectorRuntimeException cre = new ConnectorRuntimeException("Failed to parse the connector deployment descriptors");
        cre.initCause(ex);
        _logger.log(Level.SEVERE, "rardeployment.connector_descriptor_parse_error", moduleDir);
        _logger.log(Level.SEVERE, "", cre);
        throw cre;
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
    }
}
Also used : ConnectorRuntimeException(com.sun.appserv.connectors.internal.api.ConnectorRuntimeException) ConnectorArchivist(com.sun.enterprise.connectors.deployment.util.ConnectorArchivist) SAXParseException(org.xml.sax.SAXParseException) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) IOException(java.io.IOException) File(java.io.File) ConnectorRuntime(com.sun.enterprise.connectors.ConnectorRuntime)

Example 45 with FileArchive

use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.

the class AppClientScanner method doProcess.

/**
 * This scanner will scan the given main class for annotation processing.
 * The archiveFile and libJarFiles correspond to classpath.
 * @param archiveFile
 * @param desc
 * @param classLoader
 */
private void doProcess(ReadableArchive archive, ApplicationClientDescriptor desc, ClassLoader classLoader) throws IOException {
    if (AnnotationUtils.getLogger().isLoggable(Level.FINE)) {
        AnnotationUtils.getLogger().fine("archiveFile is " + archive.getURI().toASCIIString());
        AnnotationUtils.getLogger().fine("classLoader is " + classLoader);
    }
    // always add main class
    String mainClassName = desc.getMainClassName();
    addScanClassName(mainClassName);
    // add callback handle if it exist in appclient-client.xml
    String callbackHandler = desc.getCallbackHandler();
    if (callbackHandler != null && !callbackHandler.trim().equals("")) {
        addScanClassName(desc.getCallbackHandler());
    }
    GenericAnnotationDetector detector = new GenericAnnotationDetector(managedBeanAnnotations);
    if (detector.hasAnnotationInArchive(archive)) {
        if (archive instanceof FileArchive) {
            addScanDirectory(new File(archive.getURI()));
        } else if (archive instanceof InputJarArchive) {
            /*
                 * This is during deployment, so use the faster code path using
                 * the File object.
                 */
            URI uriToAdd = archive.getURI();
            addScanJar(scanJar(uriToAdd));
        } else if (archive instanceof MultiReadableArchive) {
            /*
                 * During app client launches, scan the developer's archive
                 * which is in slot #1, not the facade archive which is in
                 * slot #0.  Also, use URIs instead of File objects because
                 * during Java Web Start launches we don't have access to
                 * File objects.
                 */
            addScanURI(scanURI(((MultiReadableArchive) archive).getURI(1)));
        }
    }
    this.classLoader = classLoader;
    // = archive;
    this.archiveFile = null;
}
Also used : InputJarArchive(com.sun.enterprise.deployment.deploy.shared.InputJarArchive) GenericAnnotationDetector(org.glassfish.deployment.common.GenericAnnotationDetector) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) MultiReadableArchive(com.sun.enterprise.deployment.deploy.shared.MultiReadableArchive) File(java.io.File) URI(java.net.URI)

Aggregations

FileArchive (com.sun.enterprise.deploy.shared.FileArchive)46 File (java.io.File)11 IOException (java.io.IOException)7 InputStream (java.io.InputStream)6 URI (java.net.URI)5 JarFile (java.util.jar.JarFile)5 Result (com.sun.enterprise.tools.verifier.Result)4 ComponentNameConstructor (com.sun.enterprise.tools.verifier.tests.ComponentNameConstructor)4 Enumeration (java.util.Enumeration)4 ApplicationClientDescriptor (com.sun.enterprise.deployment.ApplicationClientDescriptor)3 URISyntaxException (java.net.URISyntaxException)3 Manifest (java.util.jar.Manifest)3 SAXParseException (org.xml.sax.SAXParseException)3 ConnectorRuntimeException (com.sun.appserv.connectors.internal.api.ConnectorRuntimeException)2 AppClientArchivist (com.sun.enterprise.deployment.archivist.AppClientArchivist)2 InputJarArchive (com.sun.enterprise.deployment.deploy.shared.InputJarArchive)2 MultiReadableArchive (com.sun.enterprise.deployment.deploy.shared.MultiReadableArchive)2 ClosureCompiler (com.sun.enterprise.tools.verifier.apiscan.classfile.ClosureCompiler)2 URL (java.net.URL)2 Attributes (java.util.jar.Attributes)2